簡體   English   中英

如何檢查db中是否已存在某個值,如果是,那么如何獲取該行的id? android sql

[英]how to check if a value already exist in db, and if so how to get the id of that row? android sql

我創建了下一個db文件 -

String sql = ""
                + "CREATE TABLE "+ Constants.TABLE_NAME + " ("
                + Constants.NAME_ID + " INTEGER PRIMARY KEY    AUTOINCREMENT,"
                + Constants.NAME_PERSON + " TEXT"
                + ")";
        db.execSQL(sql);

現在我想知道的是,如何能夠在數據庫上運行並知道數據庫中是否存在名稱,如果是這樣,我想得到該行的id。

我能理解的是我應該使用的

Cursor c= db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy) 

但我不知道接下來應該做些什么 - 所以感謝任何幫助

你可以在你的數據庫中添加它並調用函數傳遞“被搜索的密鑰”作為參數

    public boolean checkIfExist(String name) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
                new String[] { name }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        if (cursor.moveToFirst()) {
            return true;
        }else{
            return false;
        }
    }

KEY_TITLE是表中的列名。

發出SELECT請求。 然后使用if(cursor.moveToFirst())檢查您的名稱是否已存在。 (如果至少有1個值,則moveToFirst()返回true)。 因此,如果您的值存在,則juste將使用cursor.getString(cursor.getColumnIndex("_id"));獲取其id cursor.getString(cursor.getColumnIndex("_id"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM