简体   繁体   中英

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 !

Thanks for helping!

UPDATE: I've find a misstake: INSERT INTO ... extra, html, id <- I forget the 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:

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.

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 )
    {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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