Import java.sql.*;
public class Testdemo {private static String Driver = "Com.mysql.jdbc.Driver";
private static String URL = "Jdbc:mysql:///test";
private static String user = "root";
private static String password = "";
/** * method to connect to the database */public static Connection Getcon () throws Exception {Class.forName (driver);
Connection con = drivermanager.getconnection (url, user, password);
return con;
}/** * method to close the database */public static void close (Connection con, preparedstatement PS, ResultSet rs) throws Exception {
if (rs! = null) rs.close ();
if (PS! = null) ps.close ();
if (con! = null) con.close (); }/** * Test */@SuppressWarnings ("unused") public static void main (string[] args) throws Exception {Connection C
on = null;
PreparedStatement PS1 = null;
PreparedStatement PS2 = null;
String sql = "Update bank set money=money-500 where userid=1";
String sql2 = "Update bank set money=money+500 where userid=2";
try {con = Getcon (); COn.setautocommit (FALSE);
PS1 = con.preparestatement (sql);
int result1 = Ps1.executeupdate ();
PS2 = Con.preparestatement (SQL2);
int result2 = Ps2.executeupdate ();
if (false) throw new RuntimeException ("Analog exception"); if (result1 = = 1 && result2 = = 1) {System.out.println ("Transfer succeeded.
");
Con.commit (); } else {System.out.println ("The transfer failed, has been rolled back.
");
Con.rollback ();
}} catch (Exception e) {e.printstacktrace ();
Con.rollback (); System.out.println ("The transfer failed and has been rolled back.
");
} finally {close (con, PS1, null);
Close (con, PS2, null);
}
}
}
DROP TABLE IF EXISTS Bank;
The CREATE TABLE Bank (id int (one) is not NULL, UserID int (one) is not NULL, and money varchar is not NULL, PRIMARY KEY (id));
INSERT into bank VALUES (1, 1, ' 10000 '), (2, 2, ' 10000 ');