如何在java中将sql查询的纪录以数组形式显示
时间: 2024-02-17 21:00:23 浏览: 117
list转换成string数组
你可以将查询结果封装到一个ResultSet对象中,然后遍历ResultSet对象,将每一条记录的各个字段的值存入一个数组中。具体的实现代码如下:
```java
import java.sql.*;
public class SqlToArray {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
row[i - 1] = rs.getObject(i);
}
System.out.println(Arrays.toString(row));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码会查询test数据库中的user表,并将每一条记录的各个字段的值存入一个数组中,最后将数组输出到控制台。你可以根据自己的需求对这段代码进行修改。
阅读全文