zoukankan      html  css  js  c++  java
  • JDBC事务的简单使用

    在实际功能当中,经常会碰到同时对一组数据进行增加和减少,最常见的就是交易功能。

    事务内执行的语句,要么都成功,要么都失败,如果有一句没执行成功,整个事务都不会提交的。

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBC_transactions {
        public static void main(String[] args) {
            //使用try-with-resources的方法自动关闭连接
            //首先还是先初始化驱动
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
    
            //连接数据库
            try (Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
                 Statement statement = connection.createStatement();) {
                //执行一个事务
                //首先关闭自动提交
                connection.setAutoCommit(false);
                //执行两个更新语句,一个增加某个字段,一个减少某个字段
                String sql1="update hero set hp=hp-10 where id=1";
                String sql2="update hero set hp=hp+10 where id=1";
                statement.execute(sql1);
                statement.execute(sql2);
                //手动提交
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    这句话就是关闭自动提交。

    connection.setAutoCommit(false);

    一直到

    connection.commit();

    这两句话内的sql语句就是一个事务。如果我们故意制造个错误,比如故意写错sql语句的某个关键字,编译器会报错,并且正确的sql语句不会提交。

  • 相关阅读:
    83. Remove Duplicates from Sorted List
    35. Search Insert Position
    96. Unique Binary Search Trees
    94. Binary Tree Inorder Traversal
    117. Populating Next Right Pointers in Each Node II
    116. Populating Next Right Pointers in Each Node
    111. Minimum Depth of Binary Tree
    169. Majority Element
    171. Excel Sheet Column Number
    190. Reverse Bits
  • 原文地址:https://www.cnblogs.com/lbhym/p/11708191.html
Copyright © 2011-2022 走看看