检查数据库android中是否存在记录

时间:2015-04-10 10:27:39

标签: java android

我想检查SQLite数据库中是否存在记录,这是我到目前为止所做的。当我搜索已经存在的记录时,我从列表中的EditText获取值。

    //code from activity class

    public View.OnClickListener searchStation = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        arrayAdapterList=new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1,
                list);
        String searchTextFinal=searchText.getText().toString();
        dbms.searchStation(searchTextFinal);
        Cursor cursor= dbms.searchStation(searchTextFinal);



       list.add(searchTextFinal);
        arrayAdapterList= new ArrayAdapter<String>(SearchAndReview.this,
                android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapterList);


    }
};

//来自databasehelper类的代码

   public Cursor searchStation(String name){
    SQLiteDatabase database = this.getWritableDatabase();
    String searchStationQuery = "SELECT stationName FROM review WHERE stationId='"+ name+"'";
    Cursor c =database.rawQuery(searchStationQuery,null);
    if (c != null && c.moveToFirst()) {
    }
    return c;
}

3 个答案:

答案 0 :(得分:8)

我在我的应用程序中使用此代码并且它可以实现...

LoginActivity.java

DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
String email_id = email.getText().toString();
boolean dbHelper.isExist(email_id);

// if record is exist then it will return true otherwise this method returns false


使用rawQuery

 public boolean isExist(String strEmailAdd) {
        db = this.getReadableDatabase();
        cur = db.rawQuery("SELECT * FROM " + USER_TABLE + " WHERE email_id = '" + strEmailAdd + "'", null);
        boolean exist = (cur.getCount() > 0);
        cur.close();
        db.close();
        return exist;

    }

使用db.query

public boolean isExist(String strEmailAdd){

        String whereClause = "email_id = ?";
        String[] whereArgs = new String[]{strEmailAdd};

        db = database.getWritableDatabase();
        cur = db.query(USER_TABLE, null, whereClause, whereArgs, null, null, null);
        boolean exist = (cur.getCount() > 0);
        cur.close();
        db.close();
        return exist;
}

答案 1 :(得分:2)

从表格中选择一行,你得到的结果是否存在,否则就没有。

public boolean doesStationExist(String name){
    final String query = "SELECT stationName FROM review WHERE stationId='"+name+"' LIMIT 1";
    try (SQLiteDatabase database = getReadableDatabase();
         Cursor c = database.rawQuery(query, null)) {
        return c.moveToFirst();
    }
}

顺便说一句,从rawQuery返回的光标永远不会是null

修改

更新的代码将在try块完成后关闭数据库和光标。这称为try-with-resources。

答案 2 :(得分:0)

<强> DatabaseManager.java

CGPoint

<强> MainActivity.java

UIAlertAction