2017-04-03 86 views
0

我試圖在使用查詢選擇記錄後檢查記錄是否存在。我在這'管理員「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(); 

這工作時記錄時記錄不存在,它不存在。然而」根本不打印任何東西。我已經嘗試輸入數據庫中不存在的其他用戶名和密碼,但似乎沒有打印任何內容。我究竟做錯了什麼?

+0

一個不選擇*。它會將所有列移動到緩衝區。只選擇一列。第二,不要發明自己的安全。 Ping一個服務進行身份驗證。 – danny117

+0

這不涉及你的問題,但使用準備好的語句!您的代碼容易受到SQL注入攻擊。 – RichN

回答

3

docs

返回布爾值,表明此舉是否成功。

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

很顯然,如果沒有記錄然後移動沒有成功,你必須檢查它else塊。

+0

我很愚蠢,我完全錯過了。謝謝。 –

相關問題