package jdbc02;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import jdbc02.*;
public class TransactionTest {
/**
* Tom 给Jerry 汇款500元
*
* 关于事务:
* 1. 如果多个操作,每个操作使用的是自己的单独的连接,则无法保证事务。
* 2. 具体步骤
* 1) 事务操作之前,开始事务:取消Connection 的默认提交行为
* 2) 如果事务的操作都成功,则提交事务,
* 3)回滚事务
*/
@Test
public void testTransaction(){
Connection connection = null;
try {
connection = JDBCTools.getConnection2();
//开始事务:取消默认提交
connection.setAutoCommit(false);
System.out.println(connection.getAutoCommit());
String sql1 = "UPDATE users SET balance = balance-500 where id = ?";
String sql2 = "UPDATE users SET balance = balance+500 where id = ?";
update(connection, sql1, 2);
int i = 10 / 0 ;
update(connection, sql2, 1);
//提交事务
connection.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//回滚事务
try {
connection.rollback();;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
JDBCTools.release(null, null, connection);
}
//Dao dao = new Dao();
//String sql1 = "UPDATE users SET balance = balance-500 where id = 1";
//String sql2 = "UPDATE users SET balance = balance+500 where id = 2";
//
//dao.update(sql2);
//dao.update(sql1);
}
public static void update(Connection connection,String sql,Object ...args){
PreparedStatement preparedStatement = null;
try {
System.out.println(connection.getAutoCommit());
preparedStatement = connection.prepareStatement(sql);
for(int i = 0 ; i
preparedStatement.setObject(i+1, args[i]);
}
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCTools.release(null, preparedStatement, null);
}
}
}
上面是出错时的代码,应该是没问题的,是为了学习事务写的测试代码,但却一直不能实现回滚。
直接说解决方法吧,因为mysql数据库默认表不支持事务回滚...
修改Table Type为 innoDB就可以了。