-1

我将字符串传递给下面的代码,它给出了错误:

Error: 08-24 12:57:55.583: E/AndroidRuntime(11640): android.database.sqlite.SQLiteException:    near "RAMDEV": syntax error: , while compiling: SELECT chnno FROM EPG WHERE title = BABA RAMDEV KA YOGA

我的代码在这里:

public String SearchChnNo(String title){

    String selectQuery = "SELECT " + chn_no + " FROM " + EPG + " WHERE " + pgm_title + " = " + title ; //error

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    String chnno = cursor.getString(1);
    return chnno;

}
4

4 回答 4

1

Lalit Poptani 的回答是正确的,但我建议您使用原始查询方法的选择参数,方式如下:

每次您需要在查询中写入值时,请改为写一个问号

然后,您必须将值本身添加到字符串数组中

在您的情况下,它将如下所示:

public String SearchChnNo(String title){

    String selectQuery = "SELECT " + chn_no + " FROM " + EPG + " WHERE " + pgm_title + " = ? " ;
    String selectionArgs [] = new String [] { title };

    SQLiteDatabase db = this.getReadableDatabase ();
    Cursor cursor = db.rawQuery ( selectQuery , selectionArgs );
    // The default value, if none is found
    String chnno = "N/A";
    if ( cursor.moveToFirst () )
        chnno = cursor.getString ( 1 );
    // Do not forget to close the cursor
    cursor.close ();
    cursor = null;
    return chnno;

}
于 2012-08-24T07:45:02.157 回答
0
   public String SearchChnNo(String title){

    String chnno = null;

   String selectQuery = "SELECT " + chn_no + " FROM " + EPG + " WHERE " + pgm_title + "   = '" + title + "'" ;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);


    if (cursor.moveToFirst()) {
        do {
            chnno = cursor.getString(cursor.getColumnIndex(chn_no));
            //chnno = cursor.getString(chn_no);
        } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    // returning
    return chnno;

  }
于 2012-08-25T06:44:22.387 回答
0

期望pgm_title是字符串,您必须放在title单引号中,

pgm_title + " = '" + title+"'"

因此,您的最终查询将是,

String selectQuery = "SELECT " + chn_no + " FROM " + EPG + " WHERE " + 
                                             pgm_title + " = '" + title+"'" ;
于 2012-08-24T07:38:50.940 回答
0

要添加 Leeeeelo 和 Lalit 的答案,您真正应该做的是:

SQLiteDatabse db = this.getReadableDatabase();
Cursor cursor = db.query(EPG, new String[] {chn_no}, ""+pgm_title+"=?", new String [] { title}, null, null, null);
cursor.moveToFirst(); // that assumes there are results, you should probably make sure this returns true
String chnno = cursor.getString(1);
cursor.close();
return chnno;
于 2012-08-24T09:12:32.840 回答