Java教程

java 实现事务

本文主要是介绍java 实现事务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

java 实现事务

使用prepareStatement取代Statement

原因:prepareStatement可以避免sql注入且更加高效

开启事务

connection.setAutoCommit(false) 关闭自动提交的同时开启事务

package com.kuang.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestTransaction {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = JdbcUtil.getConnection();

            // 关闭自动提交,同时会开启事务
            connection.setAutoCommit(false);
            String sql = "UPDATE users SET `NAME`='zhangsan' WHERE id =1";
            preparedStatement = connection.prepareStatement(sql);
            int i = preparedStatement.executeUpdate();
            if (i> 0) {
                System.out.println("update1 success");
            }
            int j =1/0;// 测试失败情况

            String sql1 = "UPDATE users SET `NAME`='kuangshen' WHERE id =2";
            preparedStatement = connection.prepareStatement(sql1);
            i = preparedStatement.executeUpdate();
            if (i> 0) {
                System.out.println("update2 success");
            }
            connection.commit();
            System.out.println("成功");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            preparedStatement.close();
            connection.close();
        }
    }
}
这篇关于java 实现事务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!