JDBC使用事务
import java.sql.*;
public class JDBCTest10 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","123");
connection.setAutoCommit(false);
String sql = "update t_act set balance=? where actno=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setDouble(1,10000);
preparedStatement.setString(2,"111");
int count = preparedStatement.executeUpdate();
preparedStatement.setDouble(1,10000);
preparedStatement.setString(2,"222");
count += preparedStatement.executeUpdate();
System.out.println(count == 2 ? "转账成功" : "转账失败");
connection.commit();
sql = "select actno,balance from t_act where actno=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"111");
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
String actno = resultSet.getString("actno");
double balance = resultSet.getDouble("balance");
System.out.println(actno + "账户余额为:" + balance);
}
} catch (SQLException throwables) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}