Android Sqlite: Check if row exists in table

后端 未结 2 1478
感动是毒
感动是毒 2020-12-17 03:23

I have an array of strings that need to be checked if exists in a table before inserting them in order to avoid duplicates. What is the SQL query and how do I substitute the

相关标签:
2条回答
  • 2020-12-17 03:57

    Use SELECT EXIST to limit only the result to 1 or 0 and LIMIT 1 make the query execute faster:

    fun exists(): Boolean {
        var sql = "SELECT EXISTS (SELECT * FROM $tableName WHERE $someColumn 
            = $someValue LIMIT 1)"
        val cursor = db?.rawQuery(sql, null)
        cursor?.moveToFirst()
        return if (cursor?.getInt(0) == 1) {
            cursor?.close()
           true
        } else {
          cursor?.close()
          false
        }
    

    }

    0 讨论(0)
  • 2020-12-17 04:12

    Just do like

     Cursor cursor = null;
     String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue; 
     cursor= db.rawQuery(sql,null);
     Log("Cursor Count : " + cursor.getCount());
    
     if(cursor.getCount()>0){
      //PID Found
     }else{
     //PID Not Found 
     }
     cursor.close();
    
    0 讨论(0)
提交回复
热议问题