定义一个方法,查询stu表中的数据,将其封装为对象 ,然后装载集合,返回
![34249faea34362fb31d485701f0d6491.gif](https://img-blog.csdnimg.cn/img_convert/34249faea34362fb31d485701f0d6491.gif)
![9b06b0b46a141751d1b3b1103e536bb5.png](https://img-blog.csdnimg.cn/img_convert/9b06b0b46a141751d1b3b1103e536bb5.png)
数据库的数据如图所示
查询到的stu表数据封装成对象后,装载集合后,在IDEA上显示的结果为
![d46564c96b852a94f15b76127502f17e.png](https://img-blog.csdnimg.cn/img_convert/d46564c96b852a94f15b76127502f17e.png)
内容代码
import com.mysql.cj.jdbc.exceptions.ConnectionFeatureNotAvailableException;
import org.w3c.dom.ls.LSOutput;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class jdbcdemo6 {
public static void main(String[] args) {
List list=new jdbcdemo6().findAll();
System.out.println(list);
}
public List findAll(){
ResultSet rs=null;
Statement stmt=null;
Connection conn=null;
List list=new ArrayList();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dba?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT&allowPublicKeyRetrieval=true", "root", "123456");
String sql ="select * from stu";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
Stu stu=null;
while(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
stu=new Stu();
stu.setName(name);
stu.setAge(age);
list.add(stu);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}