2017-02-24 42 views
-3

我想從數據庫中選擇密碼,其中name =我在方法的參數中發送的名稱。我正在編寫數據庫的所有名稱,因此名稱在數據庫中爲100%。Android工作室SQLiteOpenHelper選擇從*其中...沒有這樣的列錯誤

,但我得到了以下錯誤:android.database.sqlite.SQLiteException: no such column: kristofer (code 1): , while compiling: SELECT * FROM login WHERE _name = kristofer

public String databasePassword(String name){ 
     String dbString = ""; 
     SQLiteDatabase db = getWritableDatabase(); 
     String query = "SELECT * FROM " + TABLE_LOGIN + " WHERE "+COLUMN_NAME + " = " + name; 
     //Cursor point to a location in your results 
     Cursor c = db.rawQuery(query, null); 
     //Move to the first row in your results 
     c.moveToFirst(); 

     while(!c.isAfterLast()){ 
      if(c.getString(c.getColumnIndex("_password"))!=null){ //Loop through every row in a database 
       dbString += c.getString(c.getColumnIndex("_password")); 
       dbString += "\n"; 
      } 
      c.moveToNext(); 
     } 
     db.close(); 
     return dbString; 
    } 
+0

sql的基礎知識:使用參數(最佳解決方案),或正確使用文字(不是一個好的解決方案) – Selvin

回答

0

這不是一個Android的具體問題,這是基本的SQL錯誤。該聲明應該如下所示:

SELECT * FROM login WHERE _name = "kristofer" 

如果你正確地注入自己的價值觀它會爲你做到這一點。

將「」或「」中的值視爲值/字符串,不包含引號時將其視爲要查找的列的名稱。

使用follwoing:

String[] vals = { name }; 
String query = "SELECT * FROM " + TABLE_LOGIN + " WHERE " + COLUMN_NAME + " = ?"; 
Cursor c = db.rawQuery(query, vals); 
2

要避免這樣的格式問題(和SQL注入攻擊),始終使用參數字符串值:

String query = "SELECT * FROM "+TABLE_LOGIN+" WHERE "+COLUMN_NAME+" = ?"; 
Cursor c = db.rawQuery(query, new String[]{ name }); 

如果你想從數據庫中讀取只有一個值,使用helper function,爲您管理光標:

public String databasePassword(String Name) { 
    SQLiteDatabase db = getWritableDatabase(); 
    try { 
     return DatabaseUtils.stringForQuery(db, 
       "SELECT _password FROM "+TABLE_LOGIN+" WHERE "+COLUMN_NAME+" = ?", 
       new String[]{ name }); 
    } finally { 
     db.close(); 
    } 
}