文章目录
JDBCTemplate
介绍
1. 导入jar包到lib
2.创建JdbcTemplate对象,依赖DataSource数据源
3. 调用方法,完成DML(增删改)和DQL(查)的操作
快速入门
运行前
package cn.itcast.jdbctemplate;
import cn.itcast.utils.JDBCUtils;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* JdbcTemplate入门
*/
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//创建对象
JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
//定义sql语句
String sql = "update account set balance = 5000 where id = ?";
//使用方法
template.update(sql, 13);
}
}
运行后
三月 07, 2021 10:53:17 上午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
Emp对象封装
package cn.itcast.domain;
import java.util.Date;
public class Emp {
private Integer id;
private String ename;
private Integer job_id;
private Integer mgr;
private Date joindate;
private Double salary;
private Double bonus;
private Integer dept_id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Integer getJob_id() {
return job_id;
}
public void setJob_id(Integer job_id) {
this.job_id = job_id;
}
public Integer getMgr() {
return mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getJoindate() {
return joindate;
}
public void setJoindate(Date joindate) {
this.joindate = joindate;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Double getBonus() {
return bonus;
}
public void setBonus(Double bonus) {
this.bonus = bonus;
}
public Integer getDept_id() {
return dept_id;
}
public void setDept_id(Integer dept_id) {
this.dept_id = dept_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 +
'}';
}
}
DML——执行增删改操作
update
方法
1. 修改1号salary为10000
运行前:
运行后:
2. 添加一条记录
运行前:
运行后:
3. 删除一条记录
运行前:
运行后:
DQL——执行查询操作
1. 查询1号记录并封装为map集合
2. 查询所有记录并封装为list集合
3. 查询所有记录并封装为Emp对象的list集合
原本写法:代码冗余
修改之后:精简许多