为什么这个Java的PreparedStatement抛出ArrayIndexOutOfBounds

2019-09-29 10:50发布

下面的方法,当与像称为String val = getCell("SELECT col FROM table WHERE LIKE(other_col,'?')", new String[]{"value"}); (这是SQLite的),将引发java.lang.ArrayIndexOutOfBoundsException: 0 at org.sqlite.PrepStmt.batch(PrepStmt.java:131) 任何人都可以承担我那可怜的装模作样可惜这里帮我,为什么

/**
 * Get a string representation of the first cell of the first row returned
 * by <code>sql</code>.
 *
 * @param sql        The SQL SELECT query, that may contain one or more '?'
 *                   IN parameter placeholders.
 * @param parameters A String array of parameters to insert into the SQL.
 * @return           The value of the cell, or <code>null</code> if there
 *                   was no result (or the result was <code>null</code>).
 */
public String getCell(String sql, String[] parameters) {
    String out = null;
    try {
        PreparedStatement ps = connection.prepareStatement(sql);
        for (int i = 1; i <= parameters.length; i++) {
            String parameter = parameters[i - 1];
            ps.setString(i, parameter);
        }
        ResultSet rs = ps.executeQuery();
        rs.first();
        out = rs.getString(1);
        rs.close();
        ps.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return out;
}

setString()会,在这种情况下,是ps.setString(1, "value")不应该是一个问题。 显然我错了,虽然。

提前谢谢了。

Answer 1:

失去周围的问号引号。 它应该是LIKE(other_col,?) 准备好的语句会找出你已经有了一个字符串,并添加引号本身。

(不SQLite的确实LIKE的功能LIKE(x,y)而不是运营商x LIKE y ?)



文章来源: Why is this Java PreparedStatement throwing ArrayIndexOutOfBoundsException 0 with parameterIndex = 1?