java - Oracle 12c 中使用 rs.getInt() 或 getLong() 的 Sequence.NEXTVAL 失败 - 那么它返回什么数据类型?

标签 java oracle jdbc prepared-statement sequence

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

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

TL;DR - 您不能绑定(bind)序列的名称,而应该在语句中对其进行硬编码(或使用字符串操作/连接来创建查询)。完成后,您可以使用 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);
}

关于java - Oracle 12c 中使用 rs.getInt() 或 getLong() 的 Sequence.NEXTVAL 失败 - 那么它返回什么数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28273370/

相关文章:

oracle - 如何在 Oracle DB 中选择具有 4 字节 UTF-8 字符的行?

java - Spring RDBMS 与 JDBCTemplate

oracle - 如何将 Tomcat 容器链接到 Oracle 容器

oracle - 没有更多数据可从套接字错误中读取

java - 我正在尝试验证用户名和密码

java - 如何读取Excel多个工作表并将Excel工作表的内容存储到数据库中

java - 将数据插入 SQLite

java - 为什么/如何取消检查 org.json.JSONException?

Java tomcat声音

java - 使用 JSoup 解析特定的文本值