定义一个方法,查询student表中的数据,将其封装为对象,装载进集合,通过遍历集合,从而获得数据
1,首先创建一个Student类,代表student表,成员变量表示的是student表中的列名,定义get,set方法,重写toString方法。
public class Student {
private int id;
private String name;
private int age;
private String sex;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2,创建一个StudentJDBC的主类,里面定义一个查询的方法findAll()。
3,findAll()方法里面是我们需要实现的具体步骤:
(1)获取数据库连接对象
(2)获取sql执行对象
(3)执行sql
(4)遍历结果集,对对象进行封装,并且装载进集合
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentJDBC {
public static void main(String[] args) {
//调用一下这方法,其返回值类型为List<Student>
List<Student> list = findAll();
//遍历一下集合
for (Student student : list) {
System.out.println(student);
}
}
//定义一个查询的方法
public static List<Student> findAll(){
Connection con= null;
Statement sta=null;
ResultSet res=null;
Student stu=null;
//创建一个集合,其类型为Student,用于把对象装载进集合
List<Student> list=new ArrayList<Student>();
try {
//定义sql
String sql="select *from student";
//获取数据库连接
con = DriverManager.getConnection("jdbc:mysql:///db1","root","123456");
//获取执行sql对象
sta=con.createStatement();
//执行sql,返回一个结果集
res = sta.executeQuery(sql);
//遍历结果集,封装对象,装载集合
while(res.next()){
//从数据库中获取数据
int id=res.getInt("id");
String name=res.getString("name");
int age=res.getInt("age");
String sex=res.getString("sex");
//创建Student对象
stu=new Student();//引用的复用
//把从数据库中获取的数据封装到对象里面
stu.setId(id);
stu.setName(name);
stu.setAge(age);
stu.setSex(sex);
//把对象装载进集合
list.add(stu);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//关闭资源,记得先判断非空
if (res!=null){
try {
res.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (sta!=null){
try {
sta.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//这个方法是有返回值的,不要忘了
return list;
}
}
注意:
(1)使用ResultSet中的getXXX方法时,里面的参数应该与student表中的列名相对应。
(2)关闭资源时,一定要判断非空
(3)关闭资源的顺序为:先创建的后关闭,后创建的先关闭
4,调用方法,遍历集合,得到数据。
5,控制台输出如下: