【问题标题】:Android Sqlite: Check if row exists in tableAndroid Sqlite:检查表中是否存在行
【发布时间】:2014-12-22 06:59:03
【问题描述】:

我有一个字符串数组,在插入它们之前需要检查它们是否存在于表中以避免重复。什么是 SQL 查询以及如何将以下值替换为它? :)

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

我的产品型号:

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

表格名称: product_pics

数据库名称: product_db

我知道这个声明会起作用:

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

如果产品存在或不存在,我如何正确格式化此方法以使方法返回?

【问题讨论】:

标签: java android sql sqlite


【解决方案1】:

喜欢就好

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

【讨论】:

  • 别忘了 cursor.close()
  • 别忘了 db.close()
【解决方案2】:

使用 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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2017-02-16
    • 2011-03-04
    相关资源
    最近更新 更多