问题描述
当我执行JDBC调用时,我正在使用默认的ResultSet
.令我惊讶的是,在使用next()
迭代ResultSet
之后,我可以调用first()
返回第一行.这并不意味着只使用正向ResultSet
?
I'm using the default ResultSet
when I do a JDBC call. I'm surprised that after using next()
to iterate the ResultSet
, I could call first()
to back to the first row. This is not meant by using forward only ResultSet
?
我的代码很简单:
Statement st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(rsmd.getColumnName(i) + " : " + columnValue);
}
System.out.println("");
}
rs.first();
我正在使用8.0.11版的mysql连接器
I am using 8.0.11 version of mysql connector
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
推荐答案
MySQL Connector/J的默认行为是,一旦调用.executeQuery
,就会将ResultSet
的全部内容加载到内存中.因此,即使我们的ResultSet
是TYPE_FORWARD_ONLY
,MySQL JDBC开发人员显然还是决定很好",并允许我们在这种情况下使用.first
,.absolute
等(因为整个ResultSet
在内存,并且随时可用),即使JDBC规范说了
The default behaviour for MySQL Connector/J is to load the entire contents of the ResultSet
into memory as soon as .executeQuery
is called. So, even though our ResultSet
is TYPE_FORWARD_ONLY
the MySQL JDBC developers apparently decided to be "nice" and allow us to use .first
, .absolute
, etc. in that case (because the entire ResultSet
is in memory and readily available), even though the JDBC spec says
但是,请注意,如果不能保证整个ResultSet
都在内存中,例如,如果我们在滚动浏览ResultSet
时使用st.setFetchSize(Integer.MIN_VALUE)
来流式传输" ResultSet
,则MySQL Connector/J会获胜除了.next
之外,我们什么都不能使用
Note, however, that if the entire ResultSet
is not guaranteed to be in memory, e.g., if we use st.setFetchSize(Integer.MIN_VALUE)
to "stream" the ResultSet
as we scroll through it, then MySQL Connector/J won't let us use anything but .next
or we'll get
com.mysql.jdbc.OperationNotSupportedException: Operation not supported for streaming result sets
这篇关于为什么我的结果集类型仅是正向时可以使用first()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!