JDBC_查询

1.通用的查询操作,结果返回一条数据

复制代码
//通用的查询操作
    public <T> T getInstance(Connection conn, Class<T> tClass, String sql, Object...args) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            rs = ps.executeQuery();
            //获取结果集中的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            //通过meteData获取结果集中的列数
            int columnCount = metaData.getColumnCount();
            if (rs.next()) {
                T t = tClass.newInstance();
                //处理结果集一行数据中的每一列
                for (int i = 0; i < columnCount; i++) {
                    //获取列值
                    Object columValue = rs.getObject(i+1);
                    //获取每个列的列名
                    String columLabel = metaData.getColumnLabel(i+1);

                    Field field = tClass.getDeclaredField(columLabel);
                    field.setAccessible(true);
                    field.set(t, columValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(null, ps, rs);
        }

        return null;
    }
复制代码

2.通用的查询操作,结果返回一个集合

复制代码
//通用的查询操作集合
    public <T> List<T> getForList(Connection conn, Class<T> tClass, String sql, Object...args) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            rs = ps.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();

            int columnCount = metaData.getColumnCount();
            ArrayList<T> list = new ArrayList<>();
            while (rs.next()) {
                T t = tClass.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object columValue = rs.getObject(i + 1);

                    String columnLabel = metaData.getColumnLabel(i + 1);

                    Field field = tClass.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(null, ps, rs);
        }
        return null;
    }
复制代码
posted @ 2020-11-21 21:17  Gqan  阅读(65)  评论(0编辑  收藏  举报