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();
        }
    }
}
posted @ 2022-01-05 20:57  Oh,mydream!  阅读(580)  评论(0编辑  收藏  举报