jdbc-升级 水果库存系统 BaseDao 添加 执行复杂查询方法

    //select max(age) as max_age ,  avg(age)  as avg_age from t_user
    // 28               24.5

    //select deptNo,avg(sal)  as avg_sal  from emp  group by deptNo

    /**
     * d001       3500
     * d002       3650
     * d003       2998
     */
    protected List executeComplexQuery(String sql, Object... params) {
        List list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        try {
            conn = getConn();
            psmt = conn.prepareStatement(sql);
            setParams(psmt, params);
            rs = psmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();//元数据,结果集的结构数据
            while (rs.next()) {
                int columnCount = rsmd.getColumnCount();//获取结果集的列的数据
                Object[] arr = new Object[columnCount];
                //jdbc中都是从 1 开始,所以要把 i 改成 从 1 开始
                for (int i = 1; i <= columnCount; i++) {
                    Object columnValue = rs.getObject(i);
                    //数组从 0 开始,所以要减 1
                    arr[i - 1] = columnValue;
                }
                list.add(arr);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            close(conn, psmt, rs);
        }
    }

你可能感兴趣的:(#,JDBC,java,jdbc)