zoukankan      html  css  js  c++  java
  • Java JDBC事务

    JDBC默认是自动提交,事务是关闭的,statement|preparedStatement.executeUpdate()或excute()执行增删改,执行一次就提交一次(自动同步到数据库)。

    JDBC事务示例:

     1  //从properties文件中加载数据库配置
     2         Properties properties = new Properties();
     3         InputStream inputStream =Class.forName("test.Test").getResourceAsStream("/mysql.properties");
     4         properties.load(inputStream);
     5 
     6         String driver = properties.getProperty("driver");
     7         String url = properties.getProperty("url");
     8         String user = properties.getProperty("user");
     9         String pwd=properties.getProperty("password");
    10 
    11         Class.forName(driver);
    12         Connection connection = DriverManager.getConnection(url, user, pwd);
    13         connection.setAutoCommit(false);   //关闭自动提交,此句代码会自动开启事务。默认为true,自动提交。
    14 
    15         String sql1 = "insert into student_tb (name,age,score) values (?,?,?)";
    16         PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
    17         preparedStatement1.setString(1,"chy");
    18         preparedStatement1.setInt(2,20);
    19         preparedStatement1.setInt(3,100);
    20         preparedStatement1.executeUpdate();  //放置到队列中
    21 
    22         String sql2 = "update student_tb set name=? where id=?";
    23         PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
    24         preparedStatement2.setString(1,"CoCo");
    25         preparedStatement2.setInt(2,10);
    26         preparedStatement2.executeUpdate();  //放置到队列中
    27 
    28         try{
    29             connection.commit();   //提交事务
    30         }catch (SQLException e){
    31             connection.rollback();  //失败就回滚
    32         } finally {
    33             preparedStatement1.close();
    34             preparedStatement2.close();
    35             connection.close();
    36         }
  • 相关阅读:
    支付宝 微信支付 移动支付 网站支付 开发
    2017 开源中国评比的前100个优秀开源项目
    解决error: Your local changes to the following files would be overwritten by merge
    Spring-JDBC配置
    server library[unbound] 服务未绑定解决办法
    MyEclipse安装EGit插件方法
    使用GitHub和Eclipse进行javaEE开发步骤
    Spring-AOP
    SQL-字符串连接聚合函数
    Spring-注入外部值
  • 原文地址:https://www.cnblogs.com/chy18883701161/p/11372089.html
Copyright © 2011-2022 走看看