问题描述
我添加了一个新用户,但是当我尝试使用该用户登录时,它使我的应用程序崩溃。 它告诉我没有“名称”列。 任何和所有的帮助将不胜感激。 这是我的代码:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table users " +
"(id integer primary key, name text,password text,age integer)"
);
db.execSQL(
"create table tasks " +
"(id integer primary key, name text, agemin integer,agemax integer,time integer)"
);
}
public boolean insertUser (String name, String password, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("password", password);
contentValues.put("age", age);
db.insert("users", null, contentValues);
return true;
}
public boolean checkPassword(String name, String password) {
int id = getUserIDByName(name);
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select password from users where id="+id+"", null );
String pass = res.getString(1);
return (password.equals(pass));
}
public int getUserIDByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select id from users where name="+name+"", null );
int id = res.getInt(1);
return id;
1楼
我会在下面建议,因为它可以防止 sql 注入
String query = "select id from users where name=?";
Cursor cursor = db.rawQuery(query, new String [] {name});
但是如果你想使用原始查询,那么一定要在字符串值周围加上引号。
改变
Cursor res = db.rawQuery( "select id from users where name="+name+"", null );
到
Cursor res = db.rawQuery( "select id from users where name='" + name + "'", null );
2楼
由于您在 getUserIdbyName() 函数中比较名称,因此您应该在查询中使用 colun。
public int getUserIDByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select id from users where name='"+name+"'", null );
int id = res.getInt(1);
return id;
}
整数和数字数据类型在 SQL 中很容易比较,当涉及到字符串或文本类型时,它有时非常棘手且有点困难。
希望这对你有用。
3楼
首先在name
变量周围使用引号:
Cursor res = db.rawQuery( "select id from users where name = '"+ name + "'", null );
然后改成这样:
int id = res.getInt(0);
和这个:
String pass = res.getString(0);
游标列的索引从0
。
此外,您必须使用moveFirst()
来检查Cursor
是否提取了任何行。
所以改成这样:
public boolean checkPassword(String name, String password) {
int id = getUserIDByName(name);
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select password from users where id="+id+"", null );
String pass = "";
if (res.moveFirst())
pass = res.getString(0);
return (password.equals(pass));
}
public int getUserIDByName(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select id from users where name='"+name+"'", null );
int id = 0;
if (res.moveFirst())
id = res.getInt(0);
return id;
}