问题遇到的现象和发生背景
数据库内emp表中用数据的,好像是数据没有添加成功
package day_01;
import domain.Emp;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class jdbc_emp {
public static void main(String[] args) {
List<Emp> all = new jdbc_emp().findAll();
System.out.println(all);
}
public List<Emp> findAll() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//登入数据库
conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root");
//写入mysql语句
String sql = "select * from emp";
//获取执行sql的对象
stmt = conn.createStatement();
//执行sql
rs = stmt.executeQuery(sql);
//遍历结果集,封装对象,装载集合
Emp emp = null;
list = new ArrayList<Emp>();
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");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");
//
emp = new Emp();
emp.setId(id);
emp.setEname(ename);
emp.setJob_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);
list.add(emp);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return null;
}
}
```java
package domain;
import java.sql.Date;
public class Emp {
private int id;
private String ename;
private int job_id;
private int mgr;
private Date joindate;
private double salary;
private double bonus;
private int dept_id;
public int getId() {
return id;
}
@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 +
'}';
}
public void setId(int id) {
this.id = id;
}
public void setEname(String ename) {
this.ename = ename;
}
public void setJob_id(int job_id) {
this.job_id = job_id;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public void setJoindate(Date joindate) {
this.joindate = joindate;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public String getEname() {
return ename;
}
public int getJob_id() {
return job_id;
}
public int getMgr() {
return mgr;
}
public Date getJoindate() {
return joindate;
}
public double getSalary() {
return salary;
}
public double getBonus() {
return bonus;
}
public int getDept_id() {
return dept_id;
}
}
运行结果及报错内容
null
你的sql好像没有加分号