jdbc读取数据库表

把结果集封装为List

// 通过结果集元数据封装List结果集
    public static List<Map<String, Object>> read(String sql) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn =  ...//获取连接
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = ps.getMetaData();

            // 取得结果集列数
            int columnCount = rsmd.getColumnCount();

            // 构造泛型结果集
            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
            Map<String, Object> data = null;

            // 循环结果集
            while (rs.next()) {
                data = new HashMap<String, Object>();
                // 每循环一条将列名和列值存入Map
                for (int i = 1; i < columnCount; i++) {
                    data.put(rsmd.getColumnLabel(i), rs.getObject(rsmd.getColumnLabel(i)));
                }
                // 将整条数据的Map存入到List中
                datas.add(data);
            }
            return datas;
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            //释放conn,ps,rs
        }
    }

// 通过数据库元数据获得服务器信息
   

public static void DbMeta() {
        Connection conn = null;
        try {
            conn = ...//获取连接
            DatabaseMetaData dbma = conn.getMetaData();
            System.out.println("----------数据库信息------------");
            System.out.println("数据库名称: " + dbma.getDatabaseProductName());
            System.out.println("驱动版本: " + dbma.getDriverVersion());
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

 

posted @ 2015-11-13 10:38  火光闪耀  阅读(400)  评论(0编辑  收藏  举报