Java 数据库中的Android记录存在()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2379550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:45:36  来源:igfitidea点击:

Android record exists() in database?

javaandroid

提问by Pentium10

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(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?

你看它有什么问题吗?

采纳答案by tbruyelle

Consider that mDbis your SqlLiteDatabaseclass

考虑那mDb是你的SqlLiteDatabase班级

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 _idas a Stringbut I think it should be a Long.
  • select 1is more fast than select columnNamebecause 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.
  • 我将您的参数保留_id为 aString但我认为它应该是Long.
  • select 1select columnName因为该过程不需要从 select 子句中的表中检索所有值更快。
  • 您可以将字符串select 1 from...放入静态最终常量中以加快速度。

回答by tbruyelle

Try this:

尝试这个:

In your DatabaseHelper, put this method...

在你的 DatabaseHelper 中,把这个方法...

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:

然后在您的 onClickListener 中,尝试调用您在 DatabaseHelper 中创建的方法。试试这个代码:

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

回答by Suragch

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 rawQuerybecause of the possibility of SQL injection. (For example, rawQuery Vs. database.query)

这个问题和选定的答案对我了解如何简单快速地检查记录是否存在很有帮助。但是,我看到很多地方都建议不要使用,rawQuery因为存在 SQL 注入的可能性。(例如,rawQuery 与 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.

我不知道这是否与所选答案一样快,但经过研究,它似乎更符合推荐的 Android 约定。

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.

我现在推荐@yuku 的答案,但我不会删除我的答案,因为我仍然想引导人们不要使用原始查询。

回答by Randy Sugianto 'Yuku'

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

由于您正在寻找来自“可靠和/或官方来源”的答案,因此DatabaseUtils我们在此处提供了一种名为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;
}

回答by LEMUEL ADANE

回答by Faheem

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