1.JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务;每次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚
2.JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
3.调用Connection的setAutoCommit ( false )可以取消自动提交事务
4.在所有的SQL语句成功执行后,调用commit()方法提交事务
5.在其中某个操作失败或出现异常时,调用rollback()方法回滚事务
- public class Transaction {
- @Test
- public void useTransaction() {
- Connection connection = null;
- String sql1 = "update account set balance=balance-100 where id=1";
- String sql2 = "update account set balance=balance+100 where id=2";
- PreparedStatement preparedStatement = null;
- try {
- connection = JdbcUtils.getConnection();
- //将connection设置为不自动提交
- connection.setAutoCommit(false)
- //执行第一条SQL语句
- preparedStatement = connection.prepareStatement(sql1);
- preparedStatement.executeUpdate();
- //执行第二条SQL语句
- preparedStatement = connection.prepareStatement(sql2);
- preparedStatement.executeUpdate();
- //最后进行提交
- connection.commit();
- } catch (SQLException e) {
- System.out.println("执行发生了异常,撤销执行的SQL...");
- //这里可以进行回滚,即撤销执行的SQL
- try {
- connection.rollback();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- e.printStackTrace();
- } finally {
- JdbcUtils.closeResource(null, preparedStatement, connection);
- }
- }
- }
1.当需要成批插入或者更新记录时,可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理,通常情况下比单独提交处理更有效率
2.JDBC的批量处理语句包括下面方法:
addBatch():添加需要批量处理的SQL语句或参数
executeBatch():执行批量处理语句
clearBatch():清空批处理包的语句
3.JDBC连接Mysql时,如果要使用批处理功能,需要在url中加参数:rewriteBatchedStatements=true
4.批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率提高
- public class Batch {
- @Test
- public void batch() throws Exception{
- Connection connection = JdbcUtils.getConnection();
- String sql = "insert into admin values(?,?)";
- PreparedStatement preparedStatement = connection.prepareStatement(sql);
- long start = System.currentTimeMillis();
- for (int i = 0; i < 5000; i++) {
- preparedStatement.setInt(1,i);
- preparedStatement.setString(2,"jack"+i);
- //将sql语句加入到批处理包中
- preparedStatement.addBatch();
- //当有1000条记录时,再批量执行
- if ((i+1)%1000 == 0){
- preparedStatement.executeBatch();
- //清空
- preparedStatement.clearBatch();
- }
- }
- long end = System.currentTimeMillis();
- System.out.println(end-start);
- JdbcUtils.closeResource(null,preparedStatement,connection);
- }
- }