我添加了一个新用户,但是当我尝试登录时,它使我的应用程序崩溃。它告诉我没有“名称”列。任何和所有帮助将不胜感激。这是我的代码:
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;
答案 0 :(得分:0)
我在下面建议,因为它可以防止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 );
答案 1 :(得分:0)
由于要在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中进行比较,有时非常棘手且有点困难。
希望这对您有用。
答案 2 :(得分:0)
首先在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;
}