通过jsp页面,进行对数据库的增删改查
表结构:
1.根据表结构创建实体类Emp:
public class Emp {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private BigDecimal sal;
private BigDecimal comm;
private Integer deptno;
public Emp() {
}
public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, BigDecimal sal, BigDecimal comm, Integer deptno) {
this.empno = empno;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
this.deptno = deptno;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public BigDecimal getSal() {
return sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
public BigDecimal getComm() {
return comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
@Override
public String toString() {
return "Emp{" +
"empno=" + empno +
", ename='" + ename + '\'' +
", job='" + job + '\'' +
", mgr=" + mgr +
", hiredate=" + hiredate +
", sal=" + sal +
", comm=" + comm +
", deptno=" + deptno +
'}';
}
}
2.写完实体类,我们开始写dao层(与数据库进行交互)
接口
public interface EmpDao {
List<Emp> findAll();
Emp findByEmpno(Integer empno);
void add(Emp emp);
void update(Emp emp);
void delete(Integer empno);
}
在完成增删改查功能之前,需要先获取到连接(从连接池中)
如果不懂,可以点开以下链接
DBUtils工具类的使用
数据库连接池
public class DataSourceUtils {
private static DruidDataSource dataSource;
static {
try {
Properties properties = new Properties();
InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream("database.properties");
properties.load(is);
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSourse(){
return dataSource;
}
}
然后创建接口的实现类:完成增删改查功能
public class EmpDaoImpl implements EmpDao {
@Override
public List<Emp> findAll() {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSourse());
try {
return qr.query("select * from emp", new BeanListHandler<Emp>(Emp.class));
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查找失败", e);
}
}
@Override
public Emp findByEmpno(Integer empno) {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSourse());
try {
return qr.query("select * from emp where empno=?", new BeanHandler<Emp>(Emp.class), empno);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("查询失败", e);
}
}
@Override</