SQLite:选择使用 LIKE '%?%' 和 rawQuery

Ahm*_*dad 3 sqlite android 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.  The statement has 0 parameters.
Run Code Online (Sandbox Code Playgroud)

这是我调用数据库的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

问题是什么 ?请

par*_*rsa 5

问题出在您使用的 SQL 查询上。
你在给?准备语句不可接受的字符串。 select distinct * from table_name where X like '%?%';不正确,因为?将是一个在像 '%"your_string"%' 这样的引号内带有双引号的字符串。

而是写:

select distinct * from table_name where X like ?;
Run Code Online (Sandbox Code Playgroud)

?使用“ '%your_string%'”。您也可以将其应用于您的字符串数组。

  • 已解决:我更改了 Destination='%'+Destination+'%'; 而不是 Destination="'%"+Destination+"%'" 谢谢 (3认同)
  • 欢迎。很高兴发现我的帖子帮助了人们! (2认同)