码迷,mamicode.com
首页 > 数据库 > 详细

JDBC事务的简单使用

时间:2019-10-20 17:40:37      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:ring   character   encoding   使用   create   cte   commit   sql   ati   

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

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

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语句不会提交。

JDBC事务的简单使用

标签:ring   character   encoding   使用   create   cte   commit   sql   ati   

原文地址:https://www.cnblogs.com/lbhym/p/11708191.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!