JDBC练习_select语句
练习:
定义一个方法,查询emp表的数据将其封装为对象,然后装在集合,返回。
1.定义Emp磊
2.定义方法 public List
3.实现方法 select * from emp;
代码实现
package cn.lhy.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
List<Emp> all = findAll();
all.forEach(emp -> System.out.println(emp));
}
/**
* 查询所有emp对象
* @return
*/
public static List<Emp> findAll() throws Exception {
ArrayList<Emp> list = new ArrayList<>();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "select * from emp";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
int salary = rs.getInt("salary");
int bonus = rs.getInt("bonus");
int dept_id = rs.getInt("dept_id");
list.add(new Emp(id,ename,job_id,mgr,joindate,salary,bonus,dept_id));
}
conn.close();
stmt.close();
return list;
}
}
emp类
package cn.lhy.Test;
import java.util.Date;
public class Emp {
int id;
String ename;
int job_id;
int mgr;
Date joindate;
int salary;
int bonus;
int dept_id;
public Emp(int id, String ename, int job_id, int mgr, Date joindate, int salary, int bonus, int dept_id) {
this.id = id;
this.ename = ename;
this.job_id = job_id;
this.mgr = mgr;
this.joindate = joindate;
this.salary = salary;
this.bonus = bonus;
this.dept_id = dept_id;
}
public Emp() {
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", ename='" + ename + '\'' +
", job_id=" + job_id +
", mgr=" + mgr +
", joindate=" + joindate +
", salary=" + salary +
", bonus=" + bonus +
", dept_id=" + dept_id +
'}';
}
}