java - 我应该指定什么以及何时指定 setFetchSize()?

标签 java mysql sql oracle jdbc

我看到很多 JDBC/MySQL 的“最佳实践”指南告诉我指定 setFetchSize()。

但是,我不知道何时指定,以及指定什么(语句、结果集)。

Statement.setFetchSize() or PreparedStatement.setFetchSize() 
ResultSet.setFetchSize()
  1. 在这两个中,我应该指定什么?
  2. 来自 javadocoracle documentation ,这就是我对“何时”感到困惑的地方

Java 文档

The default value is set by the Statement object that created the result set. The fetch size may be changed at any time.

Oracle 文档

Changes made to the fetch size of a statement object after a result set is produced will have no affect on that result set.

如果我错了,请纠正我。这是否意味着setFetchSize只有在查询执行之前才有效?(因此,ResultSet上的setFetchSize是没有用的?但碰巧“获取大小可能随时更改”?)

最佳答案

你应该阅读这个page来自关于结果集的官方文档。它说

By default, ResultSets are completely retrieved and stored in memory. In most cases this is the most efficient way to operate, and due to the design of the MySQL network protocol is easier to implement. If you are working with ResultSets that have a large number of rows or large values, and cannot allocate heap space in your JVM for the memory required, you can tell the driver to stream the results back one row at a time.

stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                            java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);

The combination of a forward-only, read-only result set, with a fetch size of Integer.MIN_VALUE serves as a signal to the driver to stream result sets row-by-row. After this, any result sets created with the statement will be retrieved row-by-row.

实际上,仅设置 fetchSize 对 connector-j 实现没有影响。

关于java - 我应该指定什么以及何时指定 setFetchSize()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899977/

相关文章:

Java 8 Lambda 列表到 Map<Int, List<String>>

c# - 插入包含外键的表

sql - 为什么使用 "where rownum = 1"不选择第一个有序行?

sql - 计算州级别特定存储桶中的行数

java - Windows 注册表 : How to add a Java app to startup list?

java - I/O错误: Socket closed

java - 部署到 Google Appengine 时出错

mysql设置触发器的最大行数

php - 使用php代码和代码igniter框架加载存储在mysql表中的url,名称,url是两列,diff用户diff url

mysql - 连接2个涉及同一个表的sql查询,我需要取回id