Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

java - Android Sqlite: Check if row exists in table

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...