setAutoCommit() false,表示关闭自动提交;true,开启自动提交事务;
commit()
rollback()
package com.ww.jdbc.junit;
import com.ww.jdbc_demo_01.util.JdbcUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo06 {
//修改,增加事务步骤
@Test
public void updateUser(){
//1、修改SQL语句
String sql="update user set nickname=? where id=?";
//2、获取连接
Connection connection= JdbcUtils.getConnection();
PreparedStatement preparedStatement= null;
try {
//事务---开启事务---把事务从自动,调整为手动提交
connection.setAutoCommit(false);
//3、创建PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
//4、替换替换符
preparedStatement.setString(1,"小李子22222");
preparedStatement.setInt(2,2);
//5、执行SQL
preparedStatement.executeUpdate();//********
//事务---结束事务---事务提交
connection.commit();
} catch (SQLException e) {
try {
//事务---结束事务---事务回滚
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} finally {
//6、释放资源
JdbcUtils.closeAll(null,preparedStatement,connection);
}
}
}
转账案例:
1、准备数据库表
account
2、需求
zs给ls转了100
3、分析
zs要从他的帐号里面扣出100
ls要往他的帐号增加100
4、代码
//转账,通过事务实现
@Test
public void zhuangZhang(){
//1、准备好SQL
String sql="update account set money=money+? where uname=?";
// update account set money=money+(-100) where uname='zs';
// update account set money=money+100 where uname='ls';
//获取连接
Connection connection=JdbcUtils.getConnection();
PreparedStatement preparedStatement01=null;
PreparedStatement preparedStatement02=null;
try {
//开启手动提交事务
connection.setAutoCommit(false);
//创建预编译对象
preparedStatement01=connection.prepareStatement(sql);
preparedStatement02=connection.prepareStatement(sql);
//替换替换符
preparedStatement01.setDouble(1,-100);
preparedStatement01.setString(2,"zs");
preparedStatement02.setDouble(1,100);
preparedStatement02.setString(2,"ls");
//执行
preparedStatement01.executeUpdate();
preparedStatement02.executeUpdate();
//
// int i=1;
// i=i/0;
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} finally {
JdbcUtils.closeAll(null,preparedStatement01,null);
JdbcUtils.closeAll(null,preparedStatement02,connection);
}
}