Android SQLite:与rawQuery一起使用类似“%”的选项进行选择
我试图使用select语句从数据库的表中查询一些数据。 当我输入=?查询成功,但当我使用LIKE%?%时,我在logcat中出现以下错误:Android SQLite:与rawQuery一起使用类似“%”的选项进行选择,android,sqlite,android-sqlite,Android,Sqlite,Android Sqlite,我试图使用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.
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;
}
有什么问题?请问题在于您使用的SQL查询。 你在付出吗?prepare语句不接受的字符串。 从表_name中选择distinct*,其中X类似“%”?%;不正确的原因是什么?将是包含双引号的字符串,引号类似于“%your_string%” 改为写:
select distinct * from table_name where X like ?;
为了什么?使用“%u字符串%”。您也可以将其应用于字符串数组。您应该使用:
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});
我想问题是select distinct*from+表名+。。。独特的*?将其更改为select*from…否,当我使用=?您不应该使用字符串连接,而应该使用“%”?%。尝试查询方法执行此操作,将其更改为。。喜欢将字符串更改为%%,你的意思是,在我的例子中,我需要这样做:DepartStation=%+DepartStation+%;目的地=%+目的地+%;是的,但是你忘记了“之前和之后”。所以DepartStation='%+DepartStation+';Destination='%+Destination+%'很容易检查。创建一个新的小项目,并且仅针对与preparedstatement的sql查询相关的行使用“%”?%,您将看到这不起作用。但是如果你用的话?在单独的查询中,用于参数而不是?如果尝试使用“%string%”,您将看到它是有效的。我做了同样的事情来回答你的问题:我改变了Destination='%'+Destination+'%';而不是Destination='%+Destination+%'谢谢。很高兴发现我的帖子帮助了很多人!我同意你的回答