我正在使用 ps = connection.prepareStatement("select seq.nextval from dual"); 获取序列的下一个值;
但是 getLong()
和 getInt()
都不起作用。
那么如何正确获取ResultSet
的值呢?
完整代码:
public static long seqGetNextValue(String sequence) {
Connection connection = Util.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
Long value = new Long(0);
try {
ps = connection.prepareStatement("select ? from dual");
ps.setString(1, sequence);
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}
return value;
}
异常(exception)如下,对于 getInt
它看起来是一样的:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.CharCommonAccessor.getLong(CharCommonAccessor.java:258)
at oracle.jdbc.driver.T4CVarcharAccessor.getLong(T4CVarcharAccessor.java:562)
at oracle.jdbc.driver.GeneratedStatement.getLong(GeneratedStatement.java:228)
at oracle.jdbc.driver.GeneratedScrollableResultSet.getLong(GeneratedScrollableResultSet.java:620)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getLong(DelegatingResultSet.java:228)
at util.Util.seqGetNextValue(Util.java:85)
最佳答案
PreparedStatement
无法绑定(bind)对象名称,只能绑定(bind)值。如果您尝试像上面那样绑定(bind) seq.nextval
,您实际上绑定(bind)的是字符串文字 'seq.nextval'
,因此您的代码可以有效地执行以下操作:
SELECT 'seq.nextval' -- Note that this is a string!
FROM dual
现在很明显为什么 getInt
和 getLong
不起作用 - 您不是在查询数字。
TL;DR - 您不能绑定(bind)序列的名称,而应该在语句中对其进行硬编码(或使用字符串操作/连接来创建查询)。完成后,您可以使用 getInt
或 getLong
,具体取决于您希望获得的值。例如:
try {
ps = connection.prepareStatement("select " + sequence + " from dual");
rs = ps.executeQuery();
if (rs.next()) {
value = rs.getInt(1);
}
System.out.println("Next payment Id: " + value);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Util.close(connection, rs, ps);
}
关于java - Oracle 12c 中使用 rs.getInt() 或 getLong() 的 Sequence.NEXTVAL 失败 - 那么它返回什么数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28273370/