java Android Sqlite:检查表中是否存在行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27597922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Sqlite: Check if row exists in table
提问by Pjayness
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?
如果产品存在与否,我如何正确格式化它以便该方法返回?
回答by M D
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();
回答by LEMUEL ADANE
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
}
}
}