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