首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

对JDBC的小小打包

2012-12-22 
对JDBC的小小封装今天对JDBC进行了小小的封装传入任意查询 SQL 语句,以表格的形式返回查询结果:public cla

对JDBC的小小封装
今天对JDBC进行了小小的封装
传入任意查询 SQL 语句,以表格的形式返回查询结果:

public class DB
{
    Connection conn;
   
    PreparedStatement ps = null;
   
    ResultSet rs = null;
   
    StringBuilder result = new StringBuilder();
   
    String[][] resultTable = null;

    public DB() throws Exception{
       
    }

    public String[][] queryForList(String sqlStr) throws Exception
    {
        if (sqlStr == null || sqlStr == "")
            throw new RuntimeException("缺少参数");
       
        if (!sqlStr.startsWith("select"))
            throw new RuntimeException("SQL语法错误");
        sqlStr = sqlStr.trim().replaceAll(";", "");
        //计算行数
        String countStr = "select count(*) from ( " + sqlStr + " )";
        conn = DBUtil.getConnection();
        ps = conn.prepareStatement(countStr);
        rs = ps.executeQuery();
        int rowCount = 0;
        if (rs.next())
            rowCount = rs.getInt(1) + 1;
        // 计算列数
        // 先提取select 和 from 之间的字符串
        String tempStr = sqlStr;
        tempStr = tempStr.substring("select".length(), tempStr.indexOf("from"));
        String[] array = tempStr.split(",");
        int colCount = array.length;
       
        ps = conn.prepareStatement(sqlStr);
        rs = ps.executeQuery();
        resultTable = new String[rowCount][colCount];
        resultTable[0] = tempStr.split(",");
        int rows = 1;
        while (rs.next())
        {
            int cols = 0;
            while (true)
            {
                try
                {
                    rs.getString(++cols);
                }
                catch (Exception e)
                {
                    break;
                }
            }
            String[] row = new String[cols-1];
            for (int i = 1; i < cols ; i++)
            {
                row[i - 1] = rs.getString(i);
            }
            if (rows <rowCount)
                resultTable[rows++] = row;
           
        }
       
        DBUtil.closeConnection(conn, ps, rs);
       
        for(int i=0;i<resultTable.length;i++){
            for(int j=0;j<resultTable[i].length;j++){
                System.out.print(resultTable[i][j]+" ");
            }
            System.out.println();
        }
       
        return resultTable;
    }
}select * from AA
怎么办....select * from AA
怎么办....

最好希望传入标准的SQL语句 呵呵

热点排行