Android record exists() in database?

前端 未结 6 1336
后悔当初
后悔当初 2020-12-13 10:00

I am looking to the fastest and the correct way to check if a record exists in the database:

public boolean Exists(String _id) {
    Cursor c=db.query(TABLEN         


        
相关标签:
6条回答
  • 2020-12-13 10:37

    Since you are looking for an answer from 'credible and/or official sources', here in DatabaseUtils we have a method called queryNumEntries.

    So your method could be made like this:

    public boolean Exists(String _id) {
        return DatabaseUtils.queryNumEntries(db, TABLENAME(), "_ID=?", new String[] {"1"}) > 0;
    }
    

    Or, for faster one:

    public boolean Exists(String _id) {
        return DatabaseUtils.longForQuery(db, "select count(*) from " + TABLENAME() + " where _ID=? limit 1", new String[] {"1"}) > 0;
    }
    
    0 讨论(0)
  • 2020-12-13 10:48

    This works good:

      Cursor cursor = null;
      String sql ="SELECT * FROM "+TableName+" WHERE ID="+idValue; 
      cursor= db.rawQuery(sql,null);
      Log.d("ISEXISTS","Cursor Count : " + cursor.getCount());
    
      boolean exists = (cursor.getCount() > 0);
      cursor.close();
    
    0 讨论(0)
  • 2020-12-13 10:55

    Consider that mDb is your SqlLiteDatabase class

    public boolean Exists(String _id) {
       Cursor cursor = mDb.rawQuery("select 1 from yourTable where _id=%s", 
            new String[] { _id });
       boolean exists = (cursor.getCount() > 0);
       cursor.close();
       return exists;
    }
    
    • I keep your parameter _id as a String but I think it should be a Long.
    • select 1 is more fast than select columnName because the process doesn't need to retrieve all values from the table in the select clause.
    • you can put the string select 1 from... in a static final constant to be even faster.
    0 讨论(0)
  • 2020-12-13 10:55

    This question and the selected answer were helpful to me for understanding how to simply and quickly check if a record exits. However, I've seen many places that recommend against using rawQuery because of the possibility of SQL injection. (For example, rawQuery Vs. database.query)

    So here is what I decided on:

    public boolean Exists(String searchItem) {
    
        String[] columns = { COLUMN_NAME };
        String selection = COLUMN_NAME + " =?";
        String[] selectionArgs = { searchItem };
        String limit = "1";
    
        Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
        boolean exists = (cursor.getCount() > 0);
        cursor.close();
        return exists;
    }
    

    I don't know if this is as fast as the selected answer or not, but after researching this it seems to conform to recommended Android conventions more.

    Update

    I now recommend @yuku's answer, but I won't delete mine yet because I still want to guide people away from using raw queries.

    0 讨论(0)
  • 2020-12-13 10:55

    Try this:

    In your DatabaseHelper, put this method...

    public String Exist(String user) {        
         String username="";
         SQLiteDatabase db = this.getReadableDatabase();               
    
         try { 
             Cursor c = db.query(TABLE_USER, null, KEY_USER + "=?", new String[]{String.valueOf(user)},null, null, null);                                               
    
             if (c == null) {                        
                 return username;                                   
             }
             else {    
                 c.moveToFirst();               
                 username = c.getString(c.getColumnIndex(KEY_USER)); 
             }                           
         }
    
         catch(Exception e){
             e.printStackTrace();
         }
    
         return username; 
    }
    

    then in your onClickListener, try to call the method that you create in your DatabaseHelper. Try this code:

    String myUser = txtUser.getText().toString();
    String storedUser = db.Exist(myUser);
    
    
    //If Username exist
    if (myUser.equals(storedUser)){
        Toast.makeText(getApplicationContext(), "Username already exist!", Toast.LENGTH_SHORT).show();
    
    0 讨论(0)
  • 2020-12-13 10:55

    Checkout my answer here: Android Sqlite: Check if row exists in table

    0 讨论(0)
提交回复
热议问题