简体   繁体   中英

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

i have created the next db file -

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

Now what I would like to know is, how to be able to run on the db and to know if a name already exist sin the db, and if so i would like to get the id of that row.

all i can understand is that i should use the

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

but I don't have a clue what I should do next - so thanks for any kind of help

you can add this in your DB and call the function passing "to be searched key" as an argument

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

Where KEY_TITLE is the column name in your table.

Take more example on this:

AndroidSQLite AndroidSQLite with multi tables

Make a SELECT request. Then check with if(cursor.moveToFirst()) if your name is already existing. ( moveToFirst() return true if there is at least 1 value). So if your value is existing, juste get its id with cursor.getString(cursor.getColumnIndex("_id"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM