栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Day14

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Day14

Day14_JDBC方式管理事务;引入commons-dbutils工具类库以及使用(笔记)

文章目录
  • Day14_JDBC方式管理事务;引入commons-dbutils工具类库以及使用(笔记)
    • 1.JDBC方式管理事务
      • 1.1 什么是事务
      • 1.2 举例代码 转账
    • 2.引入commons-dbutils工具类库以及使
      • 2.1 简介
      • 2.2 操作步骤
      • 2.3 准备工作之工具类
      • 2.4 准备工作之接口(2.5-2.8都是对此接口实现重写的方法代码)
      • 2.5 使用ResultSetHandler的实现类BeanListHandler
      • 2.6 使用ResultSetHandler的实现类BeanHandler
      • 2.7 使用ResultSetHandler的实现类ScalarHandler
      • 2.8 其他的qr.update方法
      • 2.9 总结

1.JDBC方式管理事务 1.1 什么是事务
事务: 针对关系型数据库的一种机制
  就是在执行业务操作过程中,同时执行多个sql或者多张表(添加/删除/修改),这些sql语句要么同时执行成功;
  要么同时执行失败;
1.2 举例代码 转账

开启事务: connection.setAutoCommit(false) ;

提交事务: connection.commit();

事务回滚:connection.rollback() ;

public class JDBCTransactionDemo {
    public static void main(String[] args) {

        //声明Connection类型变量
        Connection connection = null ;
        PreparedStatement ps = null ;
        PreparedStatement ps2 = null ;
        try {
            //没有通过jdbc管理事务-----当同时执行多条sql,中间如果存在异常,第一条件语句成功了,第二条数据失败;
            // 转账业务失败----->应该在jdbc操作转账的业务中加入事务操作!


            //使用Jdbc控制事务--->通过获取连接对象之后,加入事务的方法
            //通过工具类获取连接对象
             connection = DruidJdbcUtils.getConnection();
            //开启事务---->利用Connection的功能void setAutoCommit(boolean autoCommit):默认自动提交
            //参数为false:禁用自动提交,需要手动提交事务
            connection.setAutoCommit(false) ;

            //准备sql---参数化sql
            String sql = "update account set balance = balance - ? where id = ?" ;
            //获取预编译对象
            ps = connection.prepareStatement(sql);
            //参数赋值
            ps.setInt(1,500) ;
            ps.setInt(2,1) ;

            String sql2 = "update account set balance = balance + ? where id = ?" ;
            //获取预编译对象
            ps2 = connection.prepareStatement(sql2);
            ps2.setInt(1,500) ;
            ps2.setInt(2,2);

            //分别执行更新操作
            int count = ps.executeUpdate();

            int i = 10/0 ;

            int count2 = ps2.executeUpdate();
            System.out.println(count+"---"+count2);
            //提交事务: 如果没有问题,提交事务---数据在能永久更新
            //Connection对象的方法:void commit()
        } catch (Exception e) {
            System.out.println("执行catch语句");
            //出现异常,程序执行catch语句
            //事务回滚
            //连接对象的方法void rollback():回滚到默认在更新之前的操作
            try {
                connection.rollback() ;
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            
        }finally {
            //任何情况下finally中的代码一定会执行的,除非 只执行这个语句之前,jvm退出了 System.exit(0) ;
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            //释放资源
            DruidJdbcUtils.close(ps,connection);
            DruidJdbcUtils.close(ps2,connection);
        }
    }
}
2.引入commons-dbutils工具类库以及使 2.1 简介
commons-dbutils的官网地址: Apache组织机构旗下的开源的工具类库
https://commons.apache.org/proper/commons-dbutils/
就是被用来完成jdbc操作,简化了jdbc操作的一种书写格式(查询多条记录,将这些记录封装List中)
针对原生Jdbc的建议封装
2.2 操作步骤
完成jdbc操作
使用步骤:
1)需要导入核心的jar包 commons-dbtils.jar 
          mysql驱动jar包
          连接池--druid的jar包
          junit单元测试:核心包junit.jar以及依赖包
2)有关commons-dbtils.jar 核心接口以及核心类有哪些
 使用的执行对象:操作数据库
 org.apache.commons.dbutils.QueryRunner 里面封装就是PreparedStatement
 两个通用的方法
        query(xxx,ResultSetHandler rsh):针对dql语句来完成查询操作
        update(xxx,xx):针对dml域操作:insert into,update,delete from ....
 核心接口:ResultSetHandler:针对结果集的处理
         很多很多实现类
        BeanListHandler:可以将查询的多条记录封装到List集合中
        BeanHandler:将查询的结果集中某条记录封装到一个Java实体类中
        ScalarHandler:查询出的单行单列的数据----查询出总记录数(经常用到)  :聚合函数
                select count(id字段) from 表名 ; -----封装到Object对象中
2.3 准备工作之工具类

代码:

 
public class DruidJdbcUtils {

    //成员变量位置:提供ThreadLocal:模拟线程,每一个线程使用自己的Connection
    private static ThreadLocal t1 = new ThreadLocal<>() ;
    //声明一个DataSource类型的变量
    private static DataSource ds ;

    //无参构造私有化:目的外界不能new对象了
    private DruidJdbcUtils(){}

    //静态代码块
    static{
        try {
            //创建属性集合列表
            Properties prop = new Properties() ;
            //直接读取连接池的配置文件
            InputStream inputStream = DruidJdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            //将字节输入流的内容加载属性列表中
            prop.load(inputStream) ;
            //DruidDataSourceFactroy工厂类获取数据源对象
            ds = DruidDataSourceFactory.createDataSource(prop);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //封装一个功能:获取数据源
    public static DataSource getDataSource(){
        return  ds;
    }

    //封装一个功能:获取数据库的连接对象
    public static Connection getConnection(){
        //1)首先要从当前线程中获取连接对象
        try {
            Connection conn = t1.get();
            //2)判断conn是空的
            if(conn==null){
                //当前线程中没有开始绑定连接对象
                //3)从数据源连接池获取连接对象
                conn = ds.getConnection() ;
                //4)将当前连接对象绑定给自己的线程中
                t1.set(conn);
            }
            return conn ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null ;
    }

    //封装释放资源
    public static void close(PreparedStatement ps,Connection conn){
        close(null,ps,conn);
    }
    public static void close(ResultSet rs, PreparedStatement ps,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();
                //需要将自己线程中的连接对象解绑
                t1.remove();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }




}
2.4 准备工作之接口(2.5-2.8都是对此接口实现重写的方法代码)
//针对员工的数据访问接口层
public interface EmployeeDao1 {


    
    List findAll() throws SQLException;


    
    Employee findEmployeeById(int id) throws SQLException;


    
    void addEmployee(Employee employee) throws SQLException;

    
    void updateEmployee(Employee employee) throws SQLException;

    
    int deleteEmployeeById(int id) throws SQLException;

    
    int getTotalCount() throws SQLException;
}
2.5 使用ResultSetHandler的实现类BeanListHandler

代码:

public class EmployeeDaoImpl implements EmployeeDao1 {
    
    @Override
    public List findAll() throws SQLException {

        //commons-dbutils的使用步骤
        //1)导入dbutilsjar包
        //2)创建数据库的执行对象
        //QueryRunner
        //public QueryRunner(DataSource ds)
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;

        //3)准备sql语句---参数化的sql---查询全部员工数据
        String sql = "select * from employee" ;

        //4)执行它的通用方法
        //query(String sql,ResultSetHandler rsh)
        //参数1:sql语句
        //参数2:结果集的处理对象:接口
        //最终目的将所有的记录封装到List中
        //public BeanListHandler(Class type) :参数是存储当前类型的字节码文件对象
        List list = qr.query(sql,
                new BeanListHandler(Employee.class));
        return list;
    }
}
2.6 使用ResultSetHandler的实现类BeanHandler

代码

public class EmployeeDaoImpl implements EmployeeDao1 {
     
    @Override
    public Employee findEmployeeById(int id) throws SQLException {
        //创建执行对象
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //准备sql语句---参数化的sql
        String sql = "select * from employee where id = ?" ;
        //执行sql:将查询的这条记录封装到Employee类中
        // public  T query(String sql, ResultSetHandler rsh, Object... params)
        //参数1:sql语句
        //参数2:结果集的处理:BeanHandler对象    //有参构造 public BeanHandler(Class class)
        //参数3:给占位符号 赋值
        Employee employee = qr.query(sql, new BeanHandler(Employee.class), id);
        return employee;
    }
}
2.7 使用ResultSetHandler的实现类ScalarHandler

代码:

public class EmployeeDaoImpl implements EmployeeDao1 {
     
    @Override
    public int getTotalCount() throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //Sql
        String sql = "select count(id) from employee" ;
        //执行查询操作
        //ScalarHandler实现类  ResultSetHandler:查询出的单行单列的数据----查询出总记录数(经常用到)  :聚合函数
        //public ScalarHandler()
        Object obj = qr.query(sql, new ScalarHandler<>()) ;
        //String类有万能方法:valueOf(可以传递任意类型包括Object)---->String
        String s = String.valueOf(obj);
        //在String--->Integer的parseInt(String s)---->int
        int totalCount = Integer.parseInt(s);
        return totalCount;
    }
}
2.8 其他的qr.update方法
@Override
public void addEmployee(Employee employee) throws SQLException {
    //执行对象
    QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
    //sql
    String sql = "insert into employee (name,age,gender,address,salary) values (?,?,?,?,?)" ;
    //执行更新
    //通用的方法
    //update(String sql,Object...params)
    //参数1:sql
    //参数2:给占位符号赋值
    int count = qr.update(sql,
            employee.getName(),
            employee.getAge(),
            employee.getGender(),
            employee.getAddress(),
            employee.getSalary()
    );
    System.out.println(count);
}


@Override
public void updateEmployee(Employee employee) throws SQLException {

    //执行对象
    QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
    //sql
    String sql = "update employee set name =?,age=?,gender=?,address=?,salary=? where id = ?" ;
    //更新
    int count = qr.update(sql,
            employee.getName(),
            employee.getAge(),
            employee.getGender(),
            employee.getAddress(),
            employee.getSalary(),
            employee.getId());
    System.out.println(count);
}


@Override
public int deleteEmployeeById(int id) throws SQLException {
    //执行对象
    QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
    //sql
    String sql = "delete from employee where id = ?" ;
    //更新
    int count = qr.update(sql,id) ;
    System.out.println(count);
    return count;
}
2.9 总结
qr.ruery这个方法的形参中的接口ResultSetHandler的实现类常用的有三种
BeanListHandler返回一个集合
BeanHandler返回一个对象实例
ScalarHandler返回一个Object对象,使用的时候需要转型
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925143.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号