步骤:加,连,语,执,释,
public List<Student> list() {
List<Student> list = new ArrayList<>();
String sql = "SELECT * FROM student";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//1.加载注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&user=root&password=123456");
System.out.println("数据库连接成功!");
//3.创建语句对象
st = conn.createStatement();
//4.执行sql
rs = st.executeQuery(sql);
while (rs.next()) {
long id = rs.getLong("id");
String name = rs.getString("name");
Integer age = rs.getInt("age");
//封装到domian组件中
Student stu = new Student(id,name,age);
//把对象包装到list中
list.add(stu);
}
System.out.println(list);
return list;
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
//5.关闭资源
try {
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally {
try {
if (st != null) {
st.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
}
}
}
}
}
}