我正在尝试使用select语句来查询数据库表中的某些数据。 当我输入 =?时查询成功,但当我使用 LIKE%?%时,我在logcat中遇到此错误:
FATAL EXCEPTION: main
Process: com.example.ahmed.bus_time_djerba4, PID: 4178
java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range. The statement has 0 parameters.
这是我调用数据库的方法:
public String QuerySQL(String DepartStation,String Destination){
String result="";
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});
if(c.getCount()==0) {result="Data not found";c.close();}
else {
while (c.moveToNext()) {
//affichage des lignes
int ligne = c.getInt(1);
String Station = c.getString(2);
String Dest = c.getString(3);
String hours = c.getString(4);
result += "\n" + ligne + "|" + Station + "-" + Dest + " " + hours;
}
c.close();
}
return result;
}
有什么问题?请
答案 0 :(得分:2)
问题在于您使用过的SQL查询
你在给?准备语句不可接受的字符串。
text2
不正确,因为select distinct * from table_name where X like '%?%';
将是一个带引号的字符串,例如'%" your_string"%'。
代替写:
?
和select distinct * from table_name where X like ?;
使用" ?
"。你也可以将它应用于你的字符串数组。
答案 1 :(得分:1)
您应该使用:
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE \"%"+DepartStation+"%\" and "+Col_4+" LIKE \"%"+Destination+"%\"", new String[]{};
代替此:
Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});