package com.itheima.sh.transaction_04;
import util.DruidJdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransferDemo {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement1 = null;
try {
connection = DruidJdbcUtil.getConnection();
connection.setAutoCommit(false);
String sql = "update account set money = money - ? where name = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDouble(1,500);
statement.setString(2,"jack");
statement.executeUpdate();
String sql1 = "update account set money = money + ? where name = ?";
statement1 = connection.prepareStatement(sql1);
statement1.setDouble(1,500);
statement1.setString(2,"rose");
statement1.executeUpdate();
connection.commit();
System.out.println("转账成功");
} catch (Exception e) {
System.out.println("转账失败");
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
DruidJdbcUtil.release(null,statement1,connection);
}
}
}
|