我正在尝试创建登录名,但是无法进行基本检查。在授权用户之前,我需要首先检查数据库中是否存在用户名。
我尝试实现类似于本文中的功能:Android sqlite how to check if a record exists 但这不起作用。
protected void onCreate(Bundle savedInstanceState) {
database = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS Account (name VARCHAR, password TEXT, email VARCHAR(1024), id INTEGER PRIMARY KEY)" );
//Add users for testing
database.execSQL("INSERT INTO Account (name, password, email) VALUES ('admin','password','admin@example.com')");
}
public boolean checkExists(String username){
//Check if exists in database
Cursor c = database.rawQuery("SELECT * FROM Account WHERE email= ' " + username + " ' ",null);
if(c.getCount() <= 0) {
c.close();
return false;
}
c.close();
return true;
}
public void loginBtn(View view){
unField = findViewById(R.id.unField);
String username = unField.getText().toString();
//Just to check if username is retrieved from EditText field
Log.i("Input:", username);
if(checkExists(username)){
Log.i("Check:", "PASSED");
}
}
编辑:该函数似乎返回false。数据库条目有什么问题吗?它似乎没有添加值。
编辑:更改间距后它可以工作:
Cursor c = database.rawQuery("SELECT * FROM Account WHERE email= '" + username + "'",null);