当前位置:Gxlcms > 数据库问题 > 二、jdbc的关于事务的接口设计

二、jdbc的关于事务的接口设计

时间:2021-07-01 10:21:17 帮助过:19人阅读

static void autoCommit() throws SQLException { // 根据URL,从Driver中获取Connection Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD); PreparedStatement statement = null; try { // 创建statement statement = connection.prepareStatement("update t_user SET name = ‘lay‘ WHERE id = 1"); // 执行statement statement.execute(); } catch (Exception e) { e.printStackTrace(); } finally { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } }

 

事务的手动提交

自动提交的模式很方便,不需要开发者关注任何事务方面的代码。但是有时候我们希望能够手动控制事务的commit或者rollback,亦或者我们希望多条语句作为一个事务提交,而不是默认的一条语句一个事务。

要做到手动提交,首先得关闭Connection的autoCommit模式,通过setAutoCommit(false)来设置。

当处于手动提交的模式,就得注意成功的时候调用connection.commit()提交事务,异常的时候connection.rollback()回滚事务。这属于典型的搭配使用规范。

commit操作将会把当前事务中sql对数据的所有修改全部持久化到数据库中,同时释放所有事务中持有的锁。

rollback操作将会撤销当前事务中所有数据的修改,同时释放所有事务中持有的锁。

两者当且仅当autoCommit=false的时候使用。

public static void manualCommit() throws SQLException {
    // 根据URL,从Driver中获取Connection
    Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
    // 设置自动提交为false
    connection.setAutoCommit(false);
    PreparedStatement statement = null;
    try {
        // 创建statement
        statement = connection.prepareStatement("update t_user SET name = ‘lay‘ WHERE id = 1");
        // 执行statement
        statement.execute();
        // 手动提交
        connection.commit();
    } catch (Exception e) {
        // 手动回滚
        connection.rollback();
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

 

总结

jdbc对事务的接口设计非常地干净基本上就是一个auto-commit的开关,我们也可以通过getAutoCommit()常看当前Connection是否是事务自动提交模式。如果需要手动控制事务,commit和rollback接口可以提交帮助。

还有一个点需要注意的是Connection的close方法也和事务有点关系。当调用了close方法时,如果当前存在未关闭的事务,事务是否在close的时候做提交需要根据不同数据库连接器的实现来判断。

二、jdbc的关于事务的接口设计

标签:两种   word   comm   连接   开关   exe   连接器   需要   alc   

人气教程排行