[英]Check if entry exist in a database
I want to check if an entry exist in my database. 我想检查数据库中是否存在条目。
I've tried: 我试过了:
private void saveIt() {
MenuItem item = menu.findItem(R.id.menu_2);
myDB = this.openOrCreateDatabase(MY_DATABASE_NAME, MODE_PRIVATE, null);
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c == null)
{
item.setIcon(R.drawable.b);
try {
myDB.execSQL("INSERT INTO "+MY_DATABASE_TABLE+" (titel, extra, html) VALUES ('"+titel.replace("'", "\"")+"','"+extra.replace("'", "\"")+"','"+html.replace("'", "\"")+"');");
}
finally
{
if (myDB != null)
myDB.close();
}
Toast.makeText(getApplicationContext(), "saved", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "already exist", Toast.LENGTH_SHORT).show();
}
myDB.close();
}
But always it says "already exist". 但它总是说“已经存在”。 I've seen my database.
我见过我的数据库。 There is no entry where
id = xxx
! id = xxx
没有条目!
Thanks for helping! 谢谢你的帮助!
UPDATE: I've find a misstake: INSERT INTO ... extra, html, id <- I forget the id! 更新:我发现了一个错误:INSERT INTO ... extra,html, id < - 我忘记了id!
This is a great community to solve problems! 这是一个解决问题的好社区!
A Cursor won't be null
but it might be empty , you need to use this: 一个Cursor不会为
null
但它可能是空的 ,你需要使用它:
if(c.getCount() > 0) {
Toast.makeText(getApplicationContext(), "already exist", Toast.LENGTH_SHORT).show();
}
else {
// Does not exist!
}
You can also use any of the Cursor#move
methods, since they return true
or false
depending on whether there is valid data in the Cursor. 您还可以使用任何
Cursor#move
方法,因为它们返回true
或false
具体取决于Cursor中是否存在有效数据。
Change 更改
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c == null)
{
to: 至:
Cursor c = myDB.rawQuery("SELECT * FROM " + MY_DATABASE_TABLE + " WHERE idwp= '" + id + "'", null);
if(c.getCount() == 0 )
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.