原因:java.sql.SQLException:列索引无效

Caused by: java.sql.SQLException: Invalid column index

我试图通过使用 Spring jdbctemplate 传递 2 列作为过滤器来删除一条记录。但是我不知道下面的代码有什么问题。我在下面提到了异常。我已经检查了 dedug,requestId 和 qtId 值即将到来。

public void deleteTxn(String sql, int requestId, int qtId) {
    try {
            jdbcTemplate.update(sql,
                    new Object[]{
                    requestId,
                    qtId
                    }); 
        } catch(Exception e) {
            //
        }
    }
}

String sql = "DELETE FROM TABLE1 WHERE COL1 = ? AND COL2 = ?";

异常:

org.springframework.jdbc.InvalidResultSetAccessException: PreparedStatementCallback; invalid ResultSet access for SQL [DELETE FROM TABLE1 WHERE COL1 = ? AND COL2 = ?]; nested exception is java.sql.SQLException: Invalid column index at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:660) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:909) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:970) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:980)

jdbcTemplate.update 有两个相似的方法签名:

  • update(java.lang.String sql, java.lang.Object... args)

  • update(java.lang.String sql, java.lang.Object[] args, int[] argTypes)

在您的情况下,选择第一个重载方法是因为您没有提供 int[] argTypes,因此您的更新语句只有一个参数,即 new Object[]{requestId, qtId}.

解决方法很简单:写jdbcTemplate.update(sql, requestId, qtId);

即可

或者,如果你想提供类型,像这样:

jdbcTemplate.update(sql, new Object[]{requestId, qtId}, 
                         new int[]{Types.BIGINT, Types.BIGINT});