开发者

Android record exists() in database?

开发者 https://www.devze.com 2022-12-22 09:03 出处:网络
I a开发者_如何学编程m looking to the fastest and the correct way to check if a record exists in the database:

I a开发者_如何学编程m 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(TABLENAME(), new String[] {"1"}, "_ID="+_id, null, null, null, null);
    if (!c.equals(null))
        return c.moveToFirst();
    return false;
}

Do you see any problem with it?


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.


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;
}


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.


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();


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


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

精彩评论

暂无评论...
验证码 换一张
取 消