JDBC MySQL开启事务
作者:互联网
通过控制事务,达到数据更新的一致性
@Test
public void test01(){
//事务
/*
connection.setAutocommit(false);
connection.rolLback( );//回滚
connection.lommit();//提交
*/
String url="jdbc:mysql://localhost:3306/kanfang";
String user = "root";
String password="123456";
Connection connection=null;
try {
connection = DriverManager.getConnection(url, user, password);
//开启事务
connection.setAutoCommit(false);
String sql1="update account set balance=balance-500 where sname = '李白'";
String sql2="update account set balance=balance+500 where sname = '杜甫'";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();
//提交事务
connection.commit();
System.out.println("转账成功!");
} catch (SQLException throwables) {
try {
//事务回滚
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
}finally {
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
标签:事务,JDBC,String,throwables,开启,printStackTrace,connection,MySQL,balance 来源: https://blog.csdn.net/m0_52376209/article/details/119322883