一、JDBC的事务管理
connection.setAutoCommit(设置):
true:关闭事务 false:开启事务
connection.rollback():事务回滚; connection.commit():事务提交;
注意事项:1、事务开启后,在catch到异常时,执行rollback()。
2、事务结束后,在catch外面最后一行提交事务commit();
在finally里面设置事务关闭,若不然则后面使用时也按照事务执行;
在finally里面设置事务关闭资源;
public class HomeWork02 {
public static void main(String[] args) throws SQLException {
Connection connection = DruidJdbcUtils.getConnection();
Emp emp = null;
PreparedStatement ps = null;
//事务管理+更新操作
try {
connection.setAutoCommit(false);
emp = new Emp(5, "顺顺", "男", "西安市");
String sql = "update student set name = ?,gender = ?,"+
"address = ? where id = ?";
ps = connection.prepareStatement(sql);
ps.setString(1, emp.getName());
ps.setString(2, emp.getGender());
ps.setString(3, emp.getAddress());
ps.setInt(4, emp.getId());
int i = ps.executeUpdate();
// int a =1/0;
System.out.println("本次更新了" + i + "行");
connection.commit();
} catch (Exception e) {
System.out.println("我进入异常了");
connection.rollback();
throw new RuntimeException(e);
} finally {
//事务执行完不会自动回归
connection.setAutoCommit(true);
DruidJdbcUtils.close(ps, connection);
}
emp = new Emp(4, "彪彪", "男", "上海市");
String sql = "update student set name = ?,gender = ?,address = ? where id = ?";
//上面已经关闭了连接对象,下面运行会出现异常
ps = connection.prepareStatement(sql);
ps.setString(1, emp.getName());
ps.setString(2, emp.getGender());
ps.setString(3, emp.getAddress());
ps.setInt(4, emp.getId());
int i = ps.executeUpdate();
// int a =1/0;
System.out.println("本次更新了" + i + "行");
// connection.rollback();
// connection.commit();
DruidJdbcUtils.close(ps, connection);
}
}
二、sql语句的批处理使用
使用批处理需要首先设置批处理开启声明rewriteBatchedStatements=true;
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/库名?rewriteBatchedStatements=true;
username=root
password=756039065
其中有三个方法:
preparestatement.addBatch():加入设置好的批处理语句(必须先set好参数)
注意!!注意!!注意!!
批处理只对DML语句(增,删,改语句)有用;
对于preparestatement对象来说只能设置一次预编译对象;
如果改变执行的sql语句,如:预编译插入,后期需要执行删除,则删除的sql语句只能为固定的sql语句。
ps.addBatch("delete from student where name = '程彪'");
其实是因为ps是statement的接口,所以可以用类似statement.update(sql)的方式执行语句。
preparestatement.executeBatch():执行批处理语句;
executeBatch()返回结果为int数组:代表每一行sql的影响记录数;
中间有语句不能执行时,不影响执行下一语句
preparestatement.clearBatch():执行完记得清除已经包含的批处理语句(不处理也没事只执行一次)
可参考:MySQL批处理 - executeBatch方法使用 - JavaShuo
三、Common-DButils封装了操纵数据库一堆方法
DQL查询语句:
执行对象.query(sql,设置返回对象形式,sql语句需要的预编译参数):
返回对象的形式是由ResultSetHandler接口决定的。(DQL语句执行时需要对返回对象做以设置)
其实现类有:BeanListHandler:将对象对象形成集合返回;
BeanHandler:返回对象实例
ScalarHandler:使用聚合函数时使用,返回单行单列数据且为object类型,需要做类型转换。
sql语句需要的预编译参数:为执行的PrepareStatement语句使用。
public List<Emp> findAll() throws SQLException {
//使用Common-DButils工具类就是使用他的QueryRunner类来作为执行对象,里面传入数据源;
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "select * from student";
//执行对象.query(sql,设置返回内容)方法;
List<Emp> emps = query.query(sql, new BeanListHandler<Emp>(Emp.class));
return emps;
}
public Emp findEmpById(int id) throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "select * from student where id = ?";
Emp emp = query.query(sql, new BeanHandler<Emp>(Emp.class), id);
return emp;
}
public int getTotalCount() throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "select count(id) from student";
Object obj = query.query(sql, new ScalarHandler<>());
int i = Integer.parseInt(String.valueOf(obj));
return i;
}
public List<Emp> findlike(String like) throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "select * from student where name like ?";
List<Emp> emps = query.query(sql, new BeanListHandler<Emp>(Emp.class),like);
return emps;
}
DML语句:
执行对象.update(sql,sql语句需要的预编译参数): 返回值为受影响行数
sql语句需要的预编译参数:为执行的PrepareStatement语句使用。
//增加员工
@Override
public int addEmp(Emp emp) throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "insert into student(id,name,gender,address) values(?,?,?,?)";
int i = query.update(sql,emp.getId(), emp.getName(), emp.getGender(), emp.getAddress());
return i;
}
//删除员工
@Override
public int deleteEmp(int id) throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "delete from student where id = ?";
int i = query.update(sql, id);
return i;
}
//更新员工
@Override
public int updateEmp(Emp emp) throws SQLException {
QueryRunner query = new QueryRunner(DruidJdbcUtils.getDataSource());
String sql = "update student set name = ?,gender = ?,address = ? where id = ?";
int i = query.update(sql, emp.getName(), emp.getGender(), emp.getAddress(), emp.getId());
return i;
}