JDBCTemplate使用


活动地址:CSDN21天学习挑战赛

JdbcTemplate 是 Spring JDBC 核心包(core)中的核心类,它可以通过配置文件、注解、Java 配置类等形式获取数据库的相关信息,实现了对 JDBC 开发过程中的驱动加载、连接的开启和关闭、SQL 语句的创建与执行、异常处理、事务处理、数据类型转换等操作的封装。我们只要对其传入SQL 语句和必要的参数即可轻松进行 JDBC 编程。

1.JDBC工具类

package cn.itcast.datasource.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    //1.定义成员变量 DataSource
     private static DataSource ds;
     static{
         //1.加载配置文件
         Properties pro=new Properties();
         try {
             pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
             //获取DataSource
             ds= DruidDataSourceFactory.createDataSource(pro);
         } catch (IOException e) {
             e.printStackTrace();
         } catch (Exception e) {
             e.printStackTrace();
         }

     }
     /*
     获取连接
      */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /**
     * 释放资源
     */
    public static void close(Statement sta,Connection con){
        if(sta!=null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void close(ResultSet rs,Statement sta, Connection con){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       close(sta,con);

    }
    /**
     * 获取连接池的方法
     */
    public static DataSource getDataSource(){
        return ds;
    }

}

2.Emp类

package cn.itcast.domain;

import java.util.Date;

/**
 * 封装Emp对象
 **/
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 Emp() {
    }
    public Emp(Integer id, String ename, Integer job_id, Integer mgr, Date joindate, Double salary, Double bonus, Integer 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 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 +
                '}';
    }
}

3.JdbcTemplate测试类

package cn.itcast.jdbc_template;

import cn.itcast.datasource.utils.JDBCUtils;
import cn.itcast.domain.Emp;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 练习DML语句
 **/
public class JdbcTemplateDemo2 {
    // 获取JDBCTemlate对象作为成员变量
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    //Junit单元测试,可以让方法独立运行
    /**
     * 1.修改1号数据的salary为10000
     */
    @Test
    public void test1(){
        //1..定义sal
        String sql="update emp1 set salary=10000 where id=?";
        //2.执行sql
        int count = template.update(sql, 1001);
        System.out.println(count);
    }
    /**
     * 2.添加一条记录
     */
    @Test
    public void test2(){
        //1..定义sal
        String sql="insert into emp1(id,ename,dept_id)values (?,?,?)";
        //2.执行sql
        int count = template.update(sql, 1015,"郭靖",10);
        System.out.println(count);
    }
    /**
     * 3.删除刚刚添加的记录
     */
    @Test
    public void test3(){
        //1..定义sal
        String sql="delete from emp1 where id=?";
        //2.执行sql
        int count = template.update(sql, 1015);
        System.out.println(count);
    }
    /**
     * 4.查询id为1001的记录,将其封装为Map集合
     * 查询长度只能是一
     */
    @Test
    public void test4(){
        //1..定义sal
        String sql="select * from emp1 where id=?";
        //2.执行sql
        Map<String, Object> map = template.queryForMap(sql,1001);
        System.out.println(map);//{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
    }
    /**
     * 5.查询所有记录,将其封装为list
     */
    @Test
    public void test5(){
        //1..定义sal
        String sql="select * from emp1";
        //2.执行sql
        List<Map<String, Object>> list = template.queryForList(sql);
        //将每一条记录封装为一个Map集合,再将所有的Map封装到一个list集合中
        for (Map<String, Object> m:list){
            System.out.println(m);
        }
    }
    /**
     * 6.查询所有记录,将其封装为emp对象的List集合
     */
    @Test
    public void test6(){
        //1..定义sal
        String sql="select * from emp1";
        //2.执行sql
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {//自己实现接口
            @Override
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp=new Emp();
                emp.setBonus(rs.getDouble("bonus"));
                emp.setDept_id(rs.getInt("dept_id"));
                emp.setEname(rs.getString("ename"));
                emp.setId(rs.getInt("id") );
                emp.setSalary(rs.getDouble("salary"));
                emp.setJoindate(rs.getDate("joindate"));
                emp.setMgr(rs.getInt("mgr"));
                emp.setJob_id(rs.getInt("job_id"));
                return emp;
            }
        });
        for (Emp emp : list) {
            System.out.println(emp);
        }

        }
    /**
     * 6.查询所有记录,将其封装为emp对象的List集合
     */
    @Test
    public void test7(){
        //1..定义sal
        String sql="select * from emp1";
        //2.执行sql
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }

    }
    /**
     * 7.查询总记录数
     */
    @Test
    public void test8(){
        //1..定义sal
        String sql="select count(*) from emp1";
        //2.执行sql
         Long total= template.queryForObject(sql,Long.class);
        System.out.println(total );

    }
    }


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值