Java事务处理事例
A账户向B账户转1000元
t_bank表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cf0adcea137b20bd17e216fcd1980705.png)
JDBCDemo04
package JDBCTest2;
import com.mysql.jdbc.PreparedStatement;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo04 {
public static void main(String[] args) {
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql="update t_bank set balance=balance- ? where bname=?";
preparedStatement =
(PreparedStatement) connection.prepareStatement(sql);
preparedStatement.setDouble(1,1000);
preparedStatement.setString(2,"A");
int num = preparedStatement.executeUpdate();
System.out.println(num);
String sql2="update t_bank set balance=balance+ ? where bname=?";
preparedStatement =
(PreparedStatement) connection.prepareStatement(sql2);
preparedStatement.setDouble(1,1000);
preparedStatement.setString(2,"B");
int num2 = preparedStatement.executeUpdate();
System.out.println(num2);
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.getClose(connection,preparedStatement,resultSet);
}
}
}