日期:2014-05-16  浏览次数:20406 次

对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;
       &nbs