# JDBC 查询返回List

**URL:** <https://www.shiqidu.com/t/topic/764>\
**Category:** 开发调优\
**Tags:** Java\
**Created:** [2021 年12 月 21 日 10:22 UTC](https://www.shiqidu.com/t/topic/764 "2021-12-21T10:22:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Eureka](https://www.shiqidu.com/user_avatar/www.shiqidu.com/eureka/32/5_2.png) [@Eureka](https://www.shiqidu.com/u/Eureka)\
发布日期： [2021 年12 月 21 日 10:22 UTC](https://www.shiqidu.com/t/topic/764/1 "2021-12-21T10:22:19Z")

</div>

```java
String JDBC_URL = "jdbc:mysql://localhost:3306/test";
String JDBC_USER = "root";
String JDBC_PASS = "root";

Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
PreparedStatement ps = conn.prepareStatement("select * from user where username = ?");
ps.setObject(1, "test");

// PreparedStatement ps = conn.prepareStatement("select count(1) as num from user");

ResultSet rs = ps.executeQuery();
// 取得数据库的列名
ResultSetMetaData rsmd = rs.getMetaData();
// 列数
int numberOfColumns = rsmd.getColumnCount();

ArrayList<Map<String, Object>> rsList = new ArrayList<Map<String, Object>>();
Map<String, Object> rsMap = null;

while (rs.next()) {
	rsMap = new HashMap<String, Object>(numberOfColumns);
	for (int i = 1; i < numberOfColumns + 1; i++) {
		rsMap.put(rsmd.getColumnName(i), rs.getObject(i));
	}
	rsList.add(rsMap);
}

conn.close();

System.out.println(rsList);

```
