为什么此Java PreparedStatement抛出ParameterIndex = 1的ArrayIndexOutOfBoundsException 0? [英] Why is this Java PreparedStatement throwing ArrayIndexOutOfBoundsException 0 with parameterIndex = 1?
问题描述
以下方法,当使用类似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)
.谁能怜悯我在这里可怜的混蛋,并帮助我为什么?
The following method, when called with something like String val = getCell("SELECT col FROM table WHERE LIKE(other_col,'?')", new String[]{"value"});
(this is SQLite), throws a java.lang.ArrayIndexOutOfBoundsException: 0 at org.sqlite.PrepStmt.batch(PrepStmt.java:131)
. Can anyone take pity on my poor bumbling here and help me with why?
/**
* 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")
,应该没有问题.显然我错了.
The setString()
would, in this case, be ps.setString(1, "value")
and should not be a problem. Obviously I'm wrong though.
非常感谢.
推荐答案
将引号引起来.它应该是LIKE(other_col,?)
.准备好的语句将弄清楚您有一个字符串,并加上引号本身.
Lose the quotes around the question mark. It should be LIKE(other_col,?)
. The prepared statement will figure out that you've got a string and add the quote marks itself.
(SQLite是否真的将LIKE
作为函数LIKE(x,y)
而不是运算符x LIKE y
来执行?)
(Does SQLite really do LIKE
as a function LIKE(x,y)
rather than an operator x LIKE y
?)
这篇关于为什么此Java PreparedStatement抛出ParameterIndex = 1的ArrayIndexOutOfBoundsException 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!