public class JDBCDemo3_ResultSet {
@Test
public void testResultSet() throws Exception {
String url = "jdbc:mysql:///test230615?useSSL=false";
String username = "";
String password = "";
Connection connection = DriverManager.getConnection(url, username, password);
String sql = "select * from account";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double money = resultSet.getDouble("money");
System.out.println(id);
System.out.println(name);
System.out.println(money);
System.out.println("----------------");
}
connection.close();
statement.close();
resultSet.close();
}
/*
* 查询account账户表数据,封装为Account对象,并存储到ArrayList集合中
* 1.定义实体类Account
* 2.查询数据,封装到Account对象中
* 3.将Account对象存入ArrayList集合中
* */
@Test
public void testResultSet2() throws Exception {
String url = "jdbc:mysql:///test230615?useSSL=false";
String username = "";
String password = "";
Connection connection = DriverManager.getConnection(url, username, password);
String sql = "select * from account";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ArrayList<Account> list = new ArrayList<>();
while (resultSet.next()){
Account account = new Account();
// 获取数据
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double money = resultSet.getDouble("money");
// 读取数据
account.setId(id);
account.setName(name);
account.setMoney(money);
// 存入ArrayList
list.add(account);
}
System.out.println(list);
connection.close();
statement.close();
resultSet.close();
}
}
JDBC ResultSet获取查询结果,并封装为Account对象,存入ArrayList中
于 2023-06-15 15:34:44 首次发布