思路:
- 先创建一个数据类
- 创建一个方法,返回值是List集合,用于将结果集中的数据打包为对象然后存储在集合中返回,
- 方法内部,先将数据库中的数据调出来,封装为一个个Employee对象,然后将对象存入集合中返回。
数据类
public class Employee {
private int id;
private String name;
private int age;
private int dep_id;
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 int getDep_id() {
return dep_id;
}
public void setDep_id(int dep_id) {
this.dep_id = dep_id;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", dep_id=" + dep_id +
'}';
}
}
封装的方法
package domain;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/*
* 封装结果集对象
* */
public class demo01 {
public static void main(String[] args) {
List<Employee> list = new demo01().findAll();
System.out.println(list);
}
public List<Employee> findAll(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Employee emp = null;
List<Employee> list = new ArrayList<Employee>();
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///db1","root","132580");
stmt = conn.createStatement();
String sql = "select * from Employee";
rs = stmt.executeQuery(sql);
while (rs.next()){
emp = new Employee();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setAge(rs.getInt(3));
emp.setDep_id(rs.getInt(4));
list.add(emp);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally {
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}