Android SQL - Check if whole row already exists in database

前端 未结 3 1544
时光取名叫无心
时光取名叫无心 2021-01-18 19:42

I\'m trying to create a simple favorites application, where you can keep your favorites pages (from the web for example).

Let\'s say I have the following data in my

3条回答
  •  执念已碎
    2021-01-18 20:11

    You can query to see if the a unique identifier is there in the database, in your case the title maybe the unique identifier of the row.

    public boolean isEntry(int title){
        String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+KEY_PROJECT_ID+" = "+"'"+project_id+"'";
        Cursor c = db.rawQuery(queryString, null);
        if(c.getCount() > 0){
            Log.i("CHECK", "true");
            return true;
        }
        else{ 
            return false;
        }
    }
    

    Here true would mean that there is a row like this, false would mean that there is no such entry.

    Now let's say are about to insert an entry into the database. Even if the method returns a true value what you can do is you could compare the other two values as in your example. After that you could call a function to return a single row from the database, like

    public String getCursor(int project_id){
        String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+KEY_PROJECT_ID+" = "+"'"+project_id+"'";
        Cursor cursor = db.rawQuery(queryString, null);
        return cursor;
    }
    

    Once you have the function you can select the TAG and URL from it and see if it matches the one in your database.

    Like this:

    Cursor cursor = db.rawQuery(queryString, null);
    String tag = "";
    String url = "";
    
    cursor.moveToFirst();
    for (int i = 0; i < cursor.getCount(); i++) {
        like_state = cursor.getString(cursor.getColumnIndex(KEY_TAG));
        url = cursor.getString(cursor.getColumnIndex(KEY_URL));
        cursor.moveToNext();
    }
    cursor.close();
    
    if(!ins_tag.equalsIgnoreCase(tag) || !ins_url.equalsIgnoreCase(url)) {
        //insert function here
    }   
    

    And as mentioned in the comments you should use the an AUTOINCREAMENT integer as a Primary Key.

提交回复
热议问题