当子字符串与数据库中的列匹配时,为 return id 创建方法

create method to return id when substring matches with column in database

我只想在数据库处理程序 class 中创建一个方法来使用游标在列和 return 行 ID 中搜索子字符串。

就像给定的 SQL 查询:

SELECT id FROM TABLE_CONTACTS WHERE phone LIKE %phone%;
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; 
  } 
} 

问题的答案:

    // 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;
}