JDBC简单的处理事务和批处理

01.package SecondStep;
02.
03.import java.sql.*;
04.
05./**
06. *
07. * 处理事务transaction 同时执行了批处理 addBatch 和
08. *
09. */
10.public class GeDemo6 {
11. public static void main(String[] args) {
12. Connection connection = null;
13. Statement statement = null;
14.
15. try {
16. Class.forName("com.mysql.jdbc.Driver");
17.
18. String url = "jdbc:mysql://localhost:3306/test";
19.
20. String user = "root";
21.
22. String password = "123";
23.
24. connection = DriverManager.getConnection(url, user, password);
25.
26. // 禁用自动提交模式
27. connection.setAutoCommit(false);
28.
29. statement = connection.createStatement();
30.
31. // 执行这两条SQL语句 如果 其中一条出现错误 那么进入异常处理 回滚事务
32. statement
33. .addBatch("insert into testtable(username,password) values('admindemo7','123456')");
34. statement
35. .addBatch("insert into testtable(username,password) values('admindemo6','456456')");
36.
37. // 将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组
38. statement.executeBatch();
39.
40. // 手动提交事务
41. connection.commit();
42.
43. // 事务提交成功 启用自动提交模式
44. connection.setAutoCommit(true);
45. } catch (ClassNotFoundException e) {
46. e.printStackTrace();
47. } catch (SQLException e) {
48. e.printStackTrace();
49. // 异常处理 回滚事务
50. try {
51. if (connection != null) {
52. // 回滚事务
53. connection.rollback();
54. // 启用自动提交模式
55. connection.setAutoCommit(true);
56. }
57. } catch (SQLException el2) {
58. el2.printStackTrace();
59. } catch (Exception el3) {
60. el3.printStackTrace();
61. }
62. } catch (Exception e) {
63. e.printStackTrace();
64. } finally {
65. try {
66. if (statement != null) {
67. statement.close();
68. }
69. if (connection != null) {
70. connection.close();
71. }
72. } catch (SQLException e) {
73. e.printStackTrace();
74. } catch (Exception e) {
75. e.printStackTrace();
76. }
77. }
78. }
79.}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值