如何检查数据库表以查找值是否已存在?

时间:2014-04-29 04:50:36

标签: android database sqlite

我是android和sqlite的新手, 我想准备代码来检查EditText中的给定值是否已经存在 是否在数据库表中?

3 个答案:

答案 0 :(得分:0)

尝试如下:

boolean editTextValue= false;
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    while(cursor.moveToNext()){
        String recorded_editTextValue=cursor.getString(cursor.getColumnIndex("editTextValue"));
        if(recorded_editTextValue.equals(new_recorded_editTextValue)){ 
            editTextValue= true;
            break;
        }
    }

    if(!editTextValue)
        // add new_record_editTextValue to database

此处: new_recorded_editTextValue 是新的插入值

recorded_editTextValue 是db

的现有值

答案 1 :(得分:-1)

使用以下函数,如果数据库表包含editext值,则返回true,其他vise将返回false

//请将TableName更改为您要在其中检查要检查的表列的值和列名的数据库表

private boolean checkValueFromDatabaseTable() {
        DatabaseHelper dbhelp = new DatabaseHelper(getActivity());
        SQLiteDatabase db = dbhelp.getReadableDatabase();

        Cursor cursor = db.rawQuery("select * from TableName where columnname ='" + edittext.getText().toString() + "'", null);
        cursor.moveToFirst();
        if (cursor.getCount() != 0) 
                    {

            //Means you have matching value in table so return true
                        return true;

        }
                    else
                    {
                       return false;
                    }
        db.close();
        db.releaseReference();
        dbhelp.close();
    }

答案 2 :(得分:-1)

    To check the value from database use this code:

    public boolean isFileExist(String edittextValue){
                String q="Select column_name from table_name WHERE column_name='"+edittextValue+"'";
                Cursor cur=sdb.rawQuery(q, null);
                boolean isExist=false;
                while(cur.moveToNext()){
                    isExist=true;
                }
                cur.close();
                return isExist;
            }

Just pass your edit text value in argument of this method
If it returns true then value exist or returns false means value does not exist