JDBC - setAutoCommit用于只读操作 [英] JDBC - setAutoCommit for read only operation

查看:552
本文介绍了JDBC - setAutoCommit用于只读操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个通用的方法创建一个数据库连接:

Let's say I have a common method which creates a DB connection:

Connection getConnection() throws SQLException {
    Connection con = ... // create the connection
    con.setAutoCommit(false);
    return con;
}

我把 setAutoCommit(false)在这里调用,因此这种方法的调用者不必担心设置它。然而,这是一个坏的做法,如果调用者执行的操作只是读取数据?是否有额外的开销?

I put the setAutoCommit(false) call here so that callers of this method never have to worry about setting it. However, is this a bad practice if the operation executed by the caller is only reading data? Is there any extra overhead?

我个人认为最好将逻辑集中在一个地方,调用方不必设置自动提交,避免代码冗余。我只是想确保它不会对只读操作产生任何不必要的开销。

My personal opinion is that it's better to centralize the logic in one place, that way callers never have to set the auto commit and this avoids code redundancy. I just wanted to make sure it didn't incur any unnecessary overhead for a read only operation.

推荐答案


我把setAutoCommit(false)调用放在这里,以便这个方法的调用者不必担心设置它。

I put the setAutoCommit(false) call here so that callers of this method never have to worry about setting it.

这是很好的IMO,我个人认为,应该永远不要在应用程序中启用自动提交模式。所以我的建议是关闭自动提交。

This is fine IMO and I personally believe that one should never ever enable auto-commit mode inside an application. So my recommendation would be to turn off auto-commit.


但是,这是一个糟糕的做法,如果调用者执行的操作只有阅读数据?是否有额外的开销?

However, is this a bad practice if the operation executed by the caller is only reading data? Is there any extra overhead?

从严格的性能角度来看,它为每个SQL语句启动和结束数据库事务这可能会降低应用程序的性能。

From a strict performance point of view, it's starting and ending a database transaction for every SQL statement that has an overhead and may decrease the performance of your application.

顺便说一句,SELECT语句受 setAutoCommit(boolean)

By the way, SELECT statements are affected by setAutoCommit(boolean) according to the javadoc:


将此连接的自动提交
模式设置为给定状态。 如果
连接处于自动提交模式,
,则所有其SQL语句将
执行并作为单独的
事务
提交。否则,它的SQL
语句被分组到
事务中,通过
调用方法commit或
终止方法rollback。默认情况下,新的
连接处于自动提交模式。

Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode.

当语句
完成时,语句
完成的时间取决于SQL的类型
语句:

The commit occurs when the statement completes. The time when the statement completes depends on the type of SQL Statement:


  • 对于DML语句插入,更新或删除以及DDL语句
    语句在
    执行完后立即完成。

  • 对于Select语句,语句

  • 对于CallableStatement对象或返回多个
    结果的语句,语句完成
    当所有相关联的结果集
    已关闭,并且所有更新
    计数和输出参数已检索

这篇关于JDBC - setAutoCommit用于只读操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆