我将字符串传递给下面的代码并且它给出了错误:
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;
}
答案 0 :(得分: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;
}
答案 1 :(得分:0)
期待pgm_title
是String,您必须将title
放入单引号中,
pgm_title + " = '" + title+"'"
因此,您的最终查询将是,
String selectQuery = "SELECT " + chn_no + " FROM " + EPG + " WHERE " +
pgm_title + " = '" + title+"'" ;
答案 2 :(得分: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;
答案 3 :(得分: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;
}