Sequence.NEXTVAL 在 Oracle 12c 中使用 rs.getInt() 或 getLong() 失败 - 那么它是什么数据类型 returns?

Sequence.NEXTVAL in Oracle 12c with rs.getInt() or getLong() fails - so what datatype it returns?

我正在使用 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;
}

下面是例外情况,因为 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)

PreparedStatements 无法绑定对象名称,只能绑定值。如果您尝试像上面那样绑定 seq.nextval,您实际上是在绑定 字符串文字 'seq.nextval',因此您的代码在执行以下操作时有效:

SELECT 'seq.nextval' -- Note that this is a string!
FROM   dual

现在很明显为什么 getIntgetLong 不起作用 - 您不是在查询数字。

TL;DR - 您不能绑定序列的名称,而应该在语句中对其进行硬编码(或使用字符串 manipulation/concatination 创建查询)。完成后,您可以使用 getIntgetLong,具体取决于您希望获得的值。例如:

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);
}