756335d6febf4ba090b33b06a081e8ba_批量更新.txt 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. public class TestTransaction {
  8. /**
  9. * @param args
  10. */
  11. public static void main(String[] args) {
  12. // TODO Auto-generated method stub
  13. Connection con = null;
  14. Statement stmt = null;
  15. ResultSet rs = null;
  16. PreparedStatement ps = null;
  17. try {
  18. Class.forName("com.mysql.jdbc.Driver");
  19. con = DriverManager.getConnection(
  20. "jdbc:mysql://localhost:3306/mydb", "root", "root");
  21. System.out.println("连接数据库成功!");
  22. stmt = con.createStatement();
  23. // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
  24. con.setAutoCommit(false);
  25. stmt.addBatch("insert into people values(078,'ding','duo')");
  26. stmt.addBatch("insert into people values(30,'nokia','ddd')");
  27. stmt.executeBatch();
  28. // 事务提交
  29. con.commit();
  30. // 设置为自动提交,改为TRUE
  31. con.setAutoCommit(true);
  32. /*
  33. * String sql = "select * from people"; rs = stmt.executeQuery(sql);
  34. * while(rs.next()){ System.out.println(rs.getString("id") + " " +
  35. * rs.getString("name")); }
  36. */
  37. } catch (ClassNotFoundException e) {
  38. e.printStackTrace();
  39. } catch (SQLException se) {
  40. se.printStackTrace();
  41. try {
  42. // 产生的任何SQL异常都需要进行回滚,并设置为系统默认的提交方式,即为TRUE
  43. if (con != null) {
  44. con.rollback();
  45. con.setAutoCommit(true);
  46. }
  47. } catch (SQLException se1) {
  48. se.printStackTrace();
  49. }
  50. } finally {
  51. try {
  52. if (rs != null) {
  53. rs.close();
  54. rs = null;
  55. }
  56. if (stmt != null) {
  57. stmt.close();
  58. stmt = null;
  59. }
  60. if (con != null) {
  61. con.close();
  62. con = null;
  63. }
  64. } catch (SQLException se) {
  65. se.printStackTrace();
  66. }
  67. }
  68. }
  69. }