JDBC Performance Checklist

49 阅读2分钟

跟进事项

Convert 逻辑优化

对 ResultSet 使用精确的 get 方法

直接读取 bytes 并返回

获取/返回数据 Pipeline

使用 PreparedStatement

使用建议

Minimizing the Use of Database Metadata Methods

总体指导原则:尽量减少对它们的使用。

Avoiding Search Patterns

Using a Dummy Query to Determine Table Characteristics

Retrieving Data

Retrieving Long Data

返回列的数量需要控制(比如避免 select *)以减少数据传输带来的网络开销

Reducing the Size of Data Retrieved

利用 API:

  • setMaxRows

  • setMaxFieldSize

  • setFetchSize

Choosing the Right Data Type

Retrieving Result Sets

使用 RS 的建议:

  • 不要使用 rs.last / rs.getRow 来获取总的记录数,直接发送 select count(*) 更好

Consider storing data in Unicode

Selecting JDBC Objects and Methods

Using Parameter Markers as Arguments to Stored Procedures

Using the Statement Object Instead of the PreparedStatement Object

The Statement object is optimized for a single execution of a SQL statement. In contrast, the PreparedStatement object is optimized for SQL statements that will be executed two or more times.

SQL 如果只会调用一次,那么优先选择 Statement 对象。

Using Batches Instead of Prepared Statements

大批量的数据插入,使用 PreparedStatement 的 addBatch/executeBatch 方法。

Choosing the Right Cursor

3 种类型的 Cursor:

  • Forward-only

  • Insensitive

  • Sensitive

Using get Methods Effectively

Always use the specific method for the data type.

总是使用确切数据类型。

尽量不要使用 getObject(xxx)。会涉及到对象的创建和回收,增加 GC 负担。

To further improve performance, provide the column number of the column being retrieved, for example, getString(1), getLong(2), and getInt(3), instead of the column name. If column numbers are not specified, network traffic is unaffected, but costly conversions and lookups increase. For example, suppose you use getString("foo") ... A driver might have to convert foo to uppercase (if necessary), and then compare foo with all the columns in the column list. If, instead, the driver went directly to result column 23, a significant amount of processing would be saved.

确认使用的是 Column Index,而不是 Column Name。

Retrieving Auto-Generated Keys

Managing Connections and Updates

Managing Connections

启用连接池。

Managing Commits in Transactions

对于事务,已经使用 setAutoCommit(false)。

对于一般查询,目前没有设置 setAutoCommit(false)。而是使用的默认行为 setAutoCommit(true),对于 readonly 类型的查询来说设置为 autocommit=true 是可以的,否则连接一致会挂在那儿得不到关闭。

Choosing the Right Transaction Model

使用的本地事务。

Using updateXXX Methods

不涉及对拿到的 ResultSet 进行数据更新

getBestRowIdentifier

拿到的 Update 语句会直接执行

Explicitly closing your JDBC resources when done with them

及时、显式的关闭不需要的资源

REF

howtodoinjava.com/java/jdbc/b… www.ibm.com/docs/en/i/7… www.progress.com/tutorials/j…

javarevisited.blogspot.com/2012/08/top…

dzone.com/refcardz/jd…