Package sample.
import java.io.BufferedReader;
import java.io.InputStreamReader;
Import the Java. SQL. Connection;
Import the Java. SQL. DriverManager;
Import the Java. SQL. SQLException;
Import Java, SQL Statement;
Public class DB__Transaction {
Public static void main (String [] args) {
//TODO automatically generated method stub
Final String J_DRIVER=". Com. Mysql. Cj. JDBC Driver ".
Final String URL="JDBC: mysql://127.0.0.1:3306/mydb? ServerTimezone=JST& CharacterEncoding=utf-8 ";
Final String USER="root";
Final String PASSWD="root";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Try {
System. The out. Println (" id into the force vibration into yuan ");
Int from_id=Integer. ParseInt (br) readLine ());
System. The out. Println (" force vibration into the id into the first ");
Int to_id=Integer. ParseInt (br) readLine ());
System. The out. Println (" the amount of vibration force ");
Int money=Integer. ParseInt (br) readLine ());
Class.forname (J_DRIVER);
The Connection con=DriverManager. GetConnection (URL, the USER, the PASSWD);
Con. SetAutoCommit (false);
Statement stmt=con.createStatement();
String SQL="update t_bank_a set zankada";
SQL +="zankada" + "money";
SQL +="where id=" + "from_id";
Int res=STMT. ExecuteUpdate (SQL);
If (res==1) {
SQL="update t_bank_b set zandaka";
SQL +="zankada" + money;
SQL +="where id=" + to_id;
Res=STMT. ExecuteUpdate (SQL);
If (res==1) {
Con.com MIT ();
System. The out. Println (" done ");
}
The else {
Con. The rollback ();
System. The out. Println (" errors (vibration) first ");
}
}
The else {
Con. The rollback ();
System. The out. Println (" errors vibration (yuan) ");
}
Con. SetAutoCommit (true);
Con. The close ();
}
The catch (a ClassNotFoundException e) {
System. The out. Println (" JDBC_ERR ");
}
The catch (SQLException e) {
System. The out. Println (" SQL_ERR ");
}
The catch (Exception e) {
System. The out. Println (" AP_ERR ");
}
}
}
The results appear
Yuan id into the force of vibration
100
Vibration into the id into the first force
200
Into the amount of vibration into force
1
SQL_ERR