public List<User> Userquery() throws SQLException, ClassNotFoundException
{
//拿到connection
Connection connection = DBConnection.getConnection();
//使用createStatement()或者预编译prepareStatement()
Statement statement = connection.createStatement();
String sql = "select * from user";
//编写sql语句,并通过executQuery方法执行,这里查询所有数据
ResultSet resultSet = statement.executeQuery(sql);
//重点:先创建list
ArrayList<User> list = new ArrayList<>();
// 循环并赋值变量
while (resultSet.next())
{
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String userpwd = resultSet.getString("userpwd");
// 每次循环,向实体类添加数据,并且作为list列表中的一行
User user = new User(id, username, userpwd);
// 把实体类想象成 list 中的一行数据,使用add方法添加
list.add(user);
}
System.out.println("执行完毕");
// 最后不要忘记关闭链接,此处省略,本人比较懒...
return list; //最后直接返回list
}
Jdbc-resultSet结果集转化为LIst<实体类>
于 2023-06-04 23:12:03 首次发布