Android sqlite如何检查记录是否存在

时间:2013-12-06 03:19:53

标签: android sqlite

我想检查记录是否存在。

这是我尝试过的:

MainActivity.class

    public void onTextChanged(CharSequence s, int start, int before, int count) {

        System.out.println("Ontext changed " + new String(s.toString()));
        strDocumentFrom = s.toString();         

        if(s.toString().isEmpty()){

        } else {

             try{
                 strTransactionDate = dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
                 //strTotalAmount = dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
                 //strVan = dbHelper.getVanByDocumentNumber(strDocumentFrom);


                 //etTransactionDate.setText(strTransactionDate);
                 //etTotalAmount.setText(strTotalAmount);
                 //Log.d("Van", "" + strVan);
                 //etVan.setText(strVan);

             } catch (SQLiteException e) {
                 e.printStackTrace();
                 Toast.makeText(ReceivingStocksHeader.this, 
                         "Document number does not exist.", Toast.LENGTH_SHORT).show();
             }

        }

DBHelper.class

            // TODO DISPLAYING RECORDS TO TRANSRCVHEADER
        public String getTransactionDateByDocumentNumber(String strDocumentNumber){
            String[] columns = new String[]{KEY_TRANSACTIONDATE};

            Cursor c = myDataBase.query(TBL_INTRANS, 
                    columns, null, 
                    null, null, null, null, null);

            if(c != null){
                c.moveToFirst();
                String date = c.getString(0);
                return date;
            } else {
                Log.d("Error", "No record exists");
            }


            return null;
        }

但它没有让它到catch块来显示toast。

我在这里做错了什么?

14 个答案:

答案 0 :(得分:90)

public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
        String dbfield, String fieldValue) {
    SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
    String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
    Cursor cursor = sqldb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();
            return false;
        }
    cursor.close();
    return true;
}

我希望这对你有用...... 如果db中已存在记录,则此函数返回true。否则返回false。

答案 1 :(得分:29)

这些都是很好的答案,但许多人忘记 关闭游标和数据库 。如果您不关闭游标或数据库,则可能会导致内存泄漏。

此外:
在按String搜索包含非字母/数字字符时,您可能会收到错误消息。例如:&#34; 1a5f9ea3-ec4b-406b-a567-e6927640db40&#34;。破折号(-)会导致unrecognized token错误。您可以通过将字符串放入数组中来克服此问题。所以养成这样查询的习惯:

public boolean hasObject(String id) {
    SQLiteDatabase db = getWritableDatabase();
    String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";

    // Add the String you are searching by here. 
    // Put it in an array to avoid an unrecognized token error 
    Cursor cursor = db.rawQuery(selectString, new String[] {id}); 

    boolean hasObject = false;
    if(cursor.moveToFirst()){
        hasObject = true;

        //region if you had multiple records to check for, use this region. 

        int count = 0;
        while(cursor.moveToNext()){
          count++;
        }
        //here, count is records found
        Log.d(TAG, String.format("%d records found", count));

        //endregion

    } 

    cursor.close();          // Dont forget to close your cursor
    db.close();              //AND your Database!
    return hasObject;
}

答案 2 :(得分:21)

你也可以看到这个:

if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}

OR

你只需检查Cursor not null,然后检查count不为0。

所以,你试试这个......

DBHelper.getReadableDatabase();

Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE    yourKey=? AND yourKey1=?", new String[]{keyValue,keyvalue1});

if (mCursor != null)
{
            return true;
/* record exist */
 }
else
{
        return false;
/* record not exist */
}

答案 3 :(得分:14)

原始查询更容易受到SQL注入攻击。我建议改用query()方法。

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

来源:here

答案 4 :(得分:9)

您可以使用SELECT EXISTS命令并使用cursorrawQuery执行该命令, 来自文档

  

EXISTS运算符始终求值为整数值0之一   和1.如果执行指定为右侧的SELECT语句   EXISTS运算符的操作数将返回一行或多行,然后是   EXISTS运算符求值为1.如果执行SELECT将返回   根本没有行,那么EXISTS运算符的计算结果为0。

答案 5 :(得分:4)

我已经尝试过本页提到的所有方法,但只有下面的方法对我来说效果很好。

Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
 showMessage("Error", "Record exist");
}
else
{
 // Inserting record
}

答案 6 :(得分:1)

SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.

if(cursor.getCount()<=0){
    Log.v("tag","if 1 "+cursor.getCount());
    return false;
}
Log.v("tag","2 else  "+cursor.getCount());

return true;

如果你不使用cursor.moveToLast();

cursor.getCount()始终给出相同的整数(1)或光标的当前位置。

答案 7 :(得分:1)

代码:

private String[] allPushColumns = { MySQLiteHelper.COLUMN_PUSH_ID,
        MySQLiteHelper.COLUMN_PUSH_TITLE, MySQLiteHelper.COLUMN_PUSH_CONTENT, MySQLiteHelper.COLUMN_PUSH_TIME,
        MySQLiteHelper.COLUMN_PUSH_TYPE, MySQLiteHelper.COLUMN_PUSH_MSG_ID}; 

public boolean checkUniqueId(String msg_id){

    Cursor cursor = database.query(MySQLiteHelper.TABLE_PUSH,
            allPushColumns, MySQLiteHelper.COLUMN_PUSH_MSG_ID + "=?", new String [] { msg_id }, null, null, MySQLiteHelper.COLUMN_PUSH_ID +" DESC");

    if(cursor.getCount() <= 0){
        return false;
    }
    return true;
}

答案 8 :(得分:1)

带有 LIMIT 1

SELECT EXISTS 快得多。

查询示例SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);

代码示例:

public boolean columnExists(String value) {
    String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
    Cursor cursor = database.rawQuery(sql, null);
    cursor.moveToFirst();

    // cursor.getInt(0) is 1 if column with value exists
    if (cursor.getInt(0) == 1) { 
        cursor.close();
        return true;
    } else {
        cursor.close();
        return false;
    }
}

答案 9 :(得分:0)

因为可能的数据泄漏了游标的最佳解决方案:

try (cursor = ...some query)

1)从API KITKAT 你可以使用资源try()

       static public List<int> AddToList(int index,int value,  List<int> input)
        {
            if (index >= input.Count)
            {
                int[] temparray = new int[index - input.Count + 1];
                input.AddRange(temparray);
            }
            return (input[index] = value);
        }

2)如果您对VARCHAR TYPE进行查询,请使用&#39; ...&#39; ,例如。 COLUMN_NAME =&#39; string_to_search&#39;

3)当你需要从beggining开始迭代时,不要使用moveToFirst()

4)避免getCount()很昂贵 - 它迭代许多记录来计算它们。它不会返回存储的变量。第二次通话时可能会有一些缓存,但第一次通话在计算之前不知道答案。

答案 10 :(得分:0)

这是一个简单的解决方案,基于dipali和Piyush Gupta发布的组合:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

答案 11 :(得分:0)

尝试使用cursor.isNull方法。 示例:

song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));

答案 12 :(得分:0)

您可以这样使用:

window.onbeforeunload

答案 13 :(得分:0)

没有得到最高投票的答案的一件事是,如果您的搜索值是文本值,则需要在其周围加上单引号“像这样”:

public boolean checkIfMyTitleExists(String title) {
    String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
    Cursor cursor = database.rawQuery(Query, null);
    if(cursor.getCount() <= 0){
        cursor.close();
        return false;
    }
    cursor.close();

    return true;
}

否则,您将收到“ SQL(查询)错误或数据库丢失”错误,就像我在 title 字段周围没有单引号的情况下所做的那样。

如果是数字值,则不需要单引号。

请参阅此SQL post for more details