简体   繁体   中英

How to check if record already exists in SQLite table

This is my database

public void DBCreate() {
    SQLITEDATABASE = getActivity().openOrCreateDatabase("FavoritesDB", Context.MODE_PRIVATE, null);
    SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS favorite(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, word VARCHAR, meaning VARCHAR);");
}

This is how I am creating new rows:

String query = "INSERT INTO favorite (word,meaning) VALUES('"+wordd+"', '"+mean+"');";
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
if (c.moveToFirst())
{      
      Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
                    SQLITEDATABASE.execSQL(query);
}
else
{
      Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}

How to check data before inserting value into table?

before inserting perform select query and check the cursor size if it is >0 than record already exist .

I am not sure why are you passing null in your query

 Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);

instead

Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your id1"});

or if you want to select all record then

Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite");

try this code:

    Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your_id_name"});
    Log("Cursor Count : " + c.getCount());
               if(c.getCount()>0)
                {
                Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();

                }
                else
                {
                   Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
                   SQLITEDATABASE.execSQL(query);
                }

And your select query should look like:

String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;

Options:

  1. If you do not want to repeat any of the values in a column, set the column setting in the CREATE method to "UNIQUE" or even "PRIMARY KEY" if the content should be the primary key to recognize. Thus you can probably avoid any repetitions without having to check.

  2. Loop through the table:

     Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite", null); if (c.getCount() > 0) { String searchString = "some word"; // word you are about to insert while (c.moveToNext()) { c.moveToFirst(); int colIndex = c.getColumnIndex("word"); String wordInCurrentRow = c.getString(colIndex); if (!(wordInCurrentRow.equals(searchString))) { // insert method } else { // do nothing Log.d("word already existing", "nothing to insert"); } } }

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