1. 程式人生 > >JDBC事務(同時操作資料庫多個表)

JDBC事務(同時操作資料庫多個表)

public class TestTransaction {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Connection con = null;

try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testquery?useUnicode=true&characterEncoding=utf8", "root", "lovo");
//當我們需要有多條DML語句一起執行的時候,首先開啟事務
con.setAutoCommit(false);//設定自動提交為false

String sql1 = "insert into t_team " +
"(f_teamName,f_teamCountry,f_teamCoach,f_teamNum,fk_groupId) " +
"values(?,?,?,?,?)";
String sql2 = "update t_group set f_groupNum = f_groupNum + 1 " +
"where pk_groupID = ?";
PreparedStatement ps1 = con.prepareStatement(sql1);
PreparedStatement ps2 = con.prepareStatement(sql2);

ps1.setString(1, "龍之隊");
ps1.setString(2, "中華人民共和國");
ps1.setString(3, "高洪波");
ps1.setInt(4, 23);
ps1.setInt(5, 2);
ps1.executeUpdate();

ps2.setInt(1, 2);
ps2.executeUpdate();

con.commit();//事務整體提交

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con.rollback();//事務回滾
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally{
if(con != null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}


}