当substring与数据库中的列匹配时,create方法返回id

时间:2015-04-07 12:00:31

标签: android android-sqlite

我只想在databasehandler类中创建一个方法来搜索列中的子字符串并使用cursor返回行id。

就像给定的SQL Query一样:

SELECT id FROM TABLE_CONTACTS WHERE phone LIKE %phone%;

2 个答案:

答案 0 :(得分:0)

String getIDIfPhone(String phone) { 
  SQLiteDatabase db = this.getReadableDatabase(); 

  Cursor c = db.rawQuery("SELECT " + ID + " FROM " + TABLE_CONTACTS + " WHERE " + PHONE + " LIKE %"+phone+"%",new String[] {id});
  if(c.moveToFirst()){ 
    int id = c.getInt(c.getColumnIndex("id"));
    return id; 
  } else { 
    return id; 
  } 
} 

答案 1 :(得分:0)

回答问题:

    // here id is primary key of my database of string data type
    String getIDIfPhone(String phone) {
    SQLiteDatabase db = this.getReadableDatabase();

    String id = null;
    String phone1 = "%" + phone + "%";
    Cursor c = db.rawQuery("SELECT " + ID + " FROM " + TABLE_CONTACTS +
            " WHERE " + PHONE + " LIKE ?",new String[]{phone1});

    if (c!=null)
    {
        if(c.moveToFirst()) {
            id = c.getString(c.getColumnIndexOrThrow(ID));
        }
    }
    return id;
}