需求背景:用户可以查询数据库中所有表的列名和数据进行展示
连接数据库并查询数据
public static void main(String[] args) { Connection connection = null; Statement statement = null; try { String url = "jdbc:postgresql://**:**/test"; Class.forName("org.postgresql.Driver"); connection= DriverManager.getConnection(url, "**", "**"); String sql ="select * from table limit 2 offset 0"; statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); convertList(resultSet); resultSet.close(); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } }
获取ResultSet 对象中列的类型和属性信息
private static List<Map<String, ?>> convertList(ResultSet rs) throws SQLException { List<Map<String, ?>> list = new ArrayList<>(); while (rs.next()) { ResultSetMetaData md = rs.getMetaData();//获取键名即列名 int columnCount = md.getColumnCount();//获取列的数量 Map<String, Object> orderedRecords = new LinkedHashMap<>(); for (int i = 1; i <= columnCount; i++) { System.out.println(md.getColumnName(i) + "---" + rs.getObject(i)); orderedRecords.put(md.getColumnName(i), rs instanceof BigInteger ? ((BigInteger) rs).longValue() : rs); } list.add(orderedRecords); } return list; }
更多使用及方法可参考:oracle官网