JDBC练习
定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回
import cn.sytest.jdbc.domain.Emp;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/*
定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回
*/
public class JDBCDemo03 {
public static void main(String[] args) {
List<Emp> list = new JDBCDemo03().findAll();
System.out.println(list);
}
public List<Emp> findAll(){
ResultSet rs = null;
Connection conn = null;
Statement stat = null;
List<Emp> list = null;
try {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2.获取连接
conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "123456");
// 3.定义数据库
String sql = "select * from emp";
// 4.获取执行sql的对象
stat = conn.createStatement();
// 5.执行sql
rs = stat.executeQuery(sql);
// 6.遍历结果集,封装对象,装载集合
Emp emp = null;
list = new ArrayList<Emp>();
while(rs.next()){
int id = rs.getInt("id");
String NAME = rs.getString("NAME");
double salary = rs.getDouble("salary");
Date join_date = rs.getDate("join_date");
int dept_id = rs.getInt("dept_id");
emp = new Emp();
emp.setId(id);
emp.setNAME(NAME);
emp.setSalary(salary);
emp.setJoin_date(join_date);
emp.setDept_id(dept_id);
// 装载集合
list.add(emp);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
import java.util.Date;
public class Emp {
private int id;
private String NAME;
private double salary;
private Date join_date;
private int dept_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 double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Date getJoin_date() {
return join_date;
}
public void setJoin_date(Date join_date) {
this.join_date = join_date;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", NAME='" + NAME + '\'' +
", salary=" + salary +
", join_date=" + join_date +
", dept_id=" + dept_id +
'}';
}
}