2009-07-09 63 views
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)。任何人都可以憐惜我可憐的笨蛋在這裏,幫我爲什麼爲什麼此Java PreparedStatement在parameterIndex = 1時拋出ArrayIndexOutOfBoundsException 0?

/** 
* 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"),不應該是一個問題。顯然我錯了。

許多在此先感謝。

回答

4

丟失問號周圍的引號。它應該是LIKE(other_col,?)。準備好的聲明會發現你已經有了一個字符串並且自己添加了引號。

(不SQLite的確實LIKE作爲函數LIKE(x,y),而不是運營商x LIKE y?)

+0

我覺得SQLite的同時做兩... X LIKE y等價於調用標量函數LIKE(X,Y) ,它允許您重新定義操作符如何重新定義函數... – Stobor 2009-07-09 04:19:50

相關問題