SQL_day_30_事务、Properties、连接池

目录

  1. 事务
  2. properties配置文件
  3. DBCP连接池

1.事务

将多个sql语句同时执行,若其中一条sql语句执行出错,则全部搁置不执行
只有全部语句都正常执行,才执行

  • 默认情况下,是执行一条SQL语句就保存一次,那么比如我需要 有三条数据同时成功同时失败,这个时候就需要开启事务机制了如果开启事务机制,执行中发生问题,会回滚到没有操作之前,相当于什么也没有发生过
// 关闭自动提交 
connection.setAutoCommit(false);
/**中间为多行sql语句
-------
statement.addBatch("insert into t_user vaules(null,null)");
statement.addBatch("insert into t_user vaules(null,null)");
statement.addBatch("insert into t_user vaules(null,null)");
*/
//提交(将所有sql语句同时提交)(若其中一个sql语句出错,则不会执行到这句话,转而执行catch中语句)
connection.commit();
//开启自动提交(为了接下来的sql语句正常执行)
connection.setAutoCommit(true);
//若出错则运行catch中的代码, 因为
catch(Exception e){
    e.printrace();
    //开启回滚
    connection.rollback();
    //开启自动提交(为了接下来的sql语句正常执行)
    connection.setAutoCommit(true);
}

2.properties配置文件

  • 目的:优化硬代码

将数据库配置文件放在一个properties文件中,方便解析键值(如下图)

在这里插入图片描述

工具类

public static Properties getProperties(String FileName) {
  if (properties != null) {
   synchronized (Properties.class) {
    if (properties != null) {
     //将创建单例对象和解析文件放在一起,运行时,只执行一次
     properties = new Properties();
     try {
      properties.load(Properties.class.getClassLoader()
        .getResourceAsStream(FileName));
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
  }
  return properties;
 }

使用(调用properties类中方法)

Properties properties = PropertiesUtil.getProperties();
     String driver = properties.getProperty("driver");
     String url = properties.getProperty("url");
     String username = properties.getProperty("username");
     String password = properties.getProperty("password");

3.DBCP连接池

  • 优点 :
  1. 资源复用 : 数据库连接得到重用,避免了频繁创建释放链接引起的大量性能开销在减少系统消耗的基础上,也增进了系统运行环境的平稳性
  2. 更快的系统响应速度 : 数据库连接池在初始化过程中,往往就已经创建了若干个数据库连接对象放到池中备用这时,连接的初始化工作已完成,对于业务请求处理而言,直接利用现有的可用连接,避免了数据库连接初始化和释放过程的时间,从而缩减了系统整体的响应时间
  3. 统一的连接管理,避免数据库连接遗漏 : 在较为完备数据库连接池中,可以根据预先的连接占用超时设定,强制回收占用连接,从而避免了常规数据库连接操作中可能出现的资源泄露情况

先导包

在这里插入图片描述

连接池工具类(单例+传properties参数)

bds = new BasicDataSource();
     //获取properties的配置参数
     Properties properties = PropertiesUtil.getProperties();
     String driver = properties.getProperty("driver");
     String url = properties.getProperty("url");
     String username = properties.getProperty("username");
     String password = properties.getProperty("password");
     //将参数复制到连接池对象中
     bds.setDriverClassName(driver);
     bds.setUrl(url);
     bds.setUsername(username);
     bds.setPassword(password);

应用

// 创建连接池对象
  BasicDataSource bds = DBCP_Util.getBasicDataSource();
  // 获取链接
  Connection conn = bds.getConnection();
  System.out.println(conn);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值