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

时间:2017-04-03 14:08:18

标签: android sqlite

我试图在使用查询选择记录后检查记录是否存在。我在表中有一条记录是“管理员”'abc123',我正在尝试使用以下代码:

     //Define our database variables that we will use to get our data.
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

    //Define our select query here, check if username and password exists.
    String selectQuery = "SELECT * FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    //If the raw query was successfull.
    if(c.moveToFirst()){

        Integer userID = c.getInt(0);
        String userName = c.getString(1);
        String userPassword = c.getString(2);

        boolean exists = (c.getCount() > 0);

        if( exists )
        {
            Log.d("Database", userID.toString());
            Log.d("Database", userName.toString());
            Log.d("Database", userPassword.toString());
        }
        else
        {
            Log.d("Database NO", "NO");
        }

    }

    c.close();
    db.close();

当记录存在时,这是有效的,但是当记录不存在时,它根本不打印任何内容。我尝试输入数据库中不存在的其他用户名和密码,但似乎没有打印任何内容。我做错了什么?

1 个答案:

答案 0 :(得分:3)

来自docs

  

返回布尔值,表示移动是否成功。

if (c.moveToFirst()) {
  ...
} else {
    // cursor is empty, print here
}

显然,如果没有记录,那么移动还没有成功,你必须在else块中查看。