【问题标题】:Why is this Java PreparedStatement throwing ArrayIndexOutOfBoundsException 0 with parameterIndex = 1?为什么这个 Java PreparedStatement 抛出 ArrayIndexOutOfBoundsException 0 且 parameterIndex = 1?
【发布时间】:2009-07-09 04:12:04
【问题描述】:

下面的方法,当用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"),应该不是问题。显然我错了。

非常感谢。

【问题讨论】:

    标签: java sql parameters prepared-statement


    【解决方案1】:

    去掉问号两边的引号。应该是LIKE(other_col,?)。准备好的语句会找出你有一个字符串并自己添加引号。

    (SQLite 真的将LIKE 作为函数LIKE(x,y) 而不是运算符x LIKE y 吗?)

    【讨论】:

    • 我觉得Sqlite两者都做... x LIKE y 相当于调用标量函数LIKE(x,y),它可以让你通过重新定义函数来重新定义算子的工作方式...
    • 上标的使用真是令人发指:-)
    • 谢谢!很简单。而且我认为我仍在使用 LIKE(x,y) 因为我已经替换了其他一些功能; SQLite 确实有 LIKE 运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2021-12-15
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多