Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker DevOps


Java JDBC 开启事务

Java 事务 大约 1109 字

代码

connection.setAutoCommit(false);:开启事务。

connection.commit();:提交事务。

connection.rollback();:回滚事务。

boolean autoCommit = connection.getAutoCommit();:是否开启食物。

public static void main(String[] args) throws Exception {
    ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
    String user = bundle.getString("user");
    String password = bundle.getString("password");
    String url = bundle.getString("url");
    String driverClass = bundle.getString("driverClass");

    Class.forName(driverClass);

    Connection connection = DriverManager.getConnection(url, user, password);
    System.out.println(connection);

    // 开启事务
    connection.setAutoCommit(false);

    // boolean autoCommit = connection.getAutoCommit();

    String sql = "update test set name = ? where id = ?";

    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setObject(1, "abc");
    preparedStatement.setObject(2, 1);

    int row = preparedStatement.executeUpdate();

    connection.commit();

    // connection.rollback();

    preparedStatement.close();
    connection.close();
}
阅读 128 · 发布于 2022-06-02

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批