String sql = "SELECT * FROM " + tableName;
// 连接对象
Connection connection = null;
// 预编译对象 PreparedStatement
PreparedStatement preparedStatement = null;
// 结果集
ResultSet resultSet = null;
try {
// 加载驱动
Class.forName(“org.postgresql.Driver”);
// 获取连接对象
connection = DriverManager.getConnection(“jdbc:postgresql://172.38.40.242:5432/ehl”, “gpadmin”, “gpadmin”);
// 获取preparedStatement
preparedStatement = connection.prepareStatement(sql);
// 执行sql语句,并返回结果集到resultSet中
resultSet = preparedStatement.executeQuery();
List<Map<String,Object>> list = new ArrayList<>();
ResultSetMetaData md = resultSet.getMetaData(); //获得结果集结构信息,元数据
int columnCount = md.getColumnCount(); //获得列数
// 遍历结果集
while (resultSet.next()) {
Map<String,Object> rowData = new HashMap<String,Object>();
for(int i = 1;i<=columnCount;i++){
rowData.put(md.getColumnName(i), resultSet.getObject(i));
}
//System.out.println(rowData);
list.add(rowData); //之前rowData在while外面,list.add()重复引用,指向同一块内存,所以值被覆盖,重复出现后面的值
}
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
resultSet.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
}