我试图从数据库中选择密码,其中name =我在方法参数中发送的名称。我正在编写数据库的所有名称,因此数据库中的名称是100%。
但是我收到以下错误: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 :(得分:2)
按如下方式编写查询
"SELECT * FROM " + TABLE_LOGIN + " WHERE "+COLUMN_NAME + " = '" + name+"'";
您遗漏了name
值附近的单引号。 Best solution is going with parameters
答案 1 :(得分: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();
}
}
答案 2 :(得分:0)
这不是Android特定的问题,它是基本的SQL错误。该声明应该如下所示:
SELECT * FROM login WHERE _name = "kristofer"
如果你正确地注入你的价值,它会为你做这件事。
""中的值或者''被视为值/字符串,没有封闭引号,它被视为要查找的列的名称。
使用以下内容:
String[] vals = { name };
String query = "SELECT * FROM " + TABLE_LOGIN + " WHERE " + COLUMN_NAME + " = ?";
Cursor c = db.rawQuery(query, vals);