在未设置为TYPE_SCROLL_SENSITIVE或INSENSITIVE的结果集上调用absolute()

时间:2017-08-04 06:47:59

标签: java database jdbc resultset

根据我的OCP研究书,以下内容并没有例外:

try(Connection conn = DriverManager.getConnection("jdbc:derby:zoo");
  Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)){

rs.absolute(0);
rs.next();
System.out.println(rs.getString(1));
}

正如你所看到的,conn.createStatement()doesen没有像ResultSet.TYPE_SCROLL_INSENSITIVE这样的参数所以结果集应该只能一次向前移动一行吗?然而他们说没有抛出任何例外。那么这是OCP书中的错误还是我在这里遗漏了什么?

此致

2 个答案:

答案 0 :(得分:1)

这是OCP书中的错误吗?还是我在这里遗漏了什么?

简短答案: OCP书中的错误。

以下更长的答案...

遇到这个问题时,我脑子里有一个完全相同的问题,所以请自己尝试一下。果然,在运行代码时,引发了以下异常:

Exception in thread "main" java.sql.SQLException: The 'absolute()' method is only allowed on scroll cursors.
  at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.EmbedResultSet.checkScrollCursor(Unknown Source)
  at org.apache.derby.impl.jdbc.EmbedResultSet.absolute(Unknown Source)
  at com.stevectest.Main.main(Main.java:11)
Caused by: ERROR XJ061: The 'absolute()' method is only allowed on scroll cursors.
  at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
  at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
  ... 7 more

这与absolute method's Javadoc一致,它指出:

抛出:SQLException-如果发生数据库访问错误;这种方法 在封闭的结果集上调用或结果集类型为 TYPE_FORWARD_ONLY

还发现selikoff.net OCP Study Guide webpage上有一个勘误条目:

572第10章#18:正确的答案应该是E。答案应该是E,而不是A,因为结果集类型不可分。错误答案Mike Constantin 2016-02-05待审核

答案 1 :(得分:0)

Oracle documentation can give you more details on why this won't create any exceptions. As per the documentation, there are default values to the parameters like 'type' and 'concurrency'.

Statement createStatement() throws SQLException

Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.

Result sets created using the returned Statement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. The holdability of the created result sets can be determined by calling getHoldability().

Returns:

a new default Statement object

Throws: SQLException - if a database access error occurs or this method is called on a closed connection

And as @MarkRotteveel already mentioned in his comment,

Also, some driver implementations are lenient and allow more than is required by JDBC, eg some drivers allow you to use absolute with a forward-only result set, as long as the row index is the current or higher

Hope this answers your question!