简体   繁体   English

Android Sqlite:检查表中是否存在行

[英]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? 什么是SQL查询以及如何将以下值替换为它? :) :)

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 表名: product_pics

Database name: product_db 数据库名称: 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? 如何正确格式化此方法,以便在产品存在时方法返回?

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

Use SELECT EXIST to limit only the result to 1 or 0 and LIMIT 1 make the query execute faster: 使用SELECT EXIST仅将结果限制为1或0,LIMIT 1使查询执行得更快:

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
    }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM