Android Sqlite: Check if row exists in table

21,632

Solution 1

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();

Solution 2

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
    }

}

Share:
21,632
Pjayness
Author by

Pjayness

Updated on March 09, 2020

Comments

  • Pjayness
    Pjayness about 4 years

    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 following values to it? :)

    ArrayList<Product> NewProducts= new ArrayList<Product>();
    

    My Product Model:

    public class Product {
        public Product()
        {
    
        }
    
        public String PID = "pid";
        public String getPID() {
            return PID;
        }
        public void setPID(String pID) {
            PID = pID;
        }
        public String getNAME() {
            return NAME;
        }
        public void setNAME(String nAME) {
            NAME = nAME;
        }
    
        public String PID = "pid";
        public String NAME = "name";
    }
    

    Table name: product_pics

    Database name: product_db

    I understand that this statement will work:

    "SELECT * FROM ' + product_pics + ' WHERE PID=' + pid +'"
    

    How do I properly format this such that the method returns if the product exists or not?

  • Alexi Akl
    Alexi Akl over 7 years
    don't forget cursor.close()
  • EtherPaul
    EtherPaul over 4 years
    and don't forget db.close()