我在Android SDK中使用SQLite数据库,我知道这是一个非常简单的问题,但是我在下面有以下功能。我正在尝试搜索用户名是否在SQL数据库中,但是我想不出如何构造查询。
如果字符串“ user”在表“ ACCOUNT_TABLE”内,则搜索的正确方法是什么?
public boolean isUser(String user){
SQLiteDatabase db = this.getReadableDatabase();
String queryString = "SELECT " + COLUMN_USERNAME + " FROM " + ACCOUNT_TABLE + " WHERE " (???);
db.close();
/*if(found in database)
return true;
else
return false;*/
}
正确的方法是使用带有rawQuery()
2个参数的方法:
SELECT
带有?
要传递的参数的占位符的sql语句String
数组,其中包含sql语句参数的所有值,并按它们在语句中出现的顺序排列rawQuery()
返回一个Cursor
,您可以检查其中是否包含任何行,并且这样做是否意味着user
您搜索的表中存在该表:
public boolean isUser(String user) {
SQLiteDatabase db = this.getReadableDatabase();
String queryString = "SELECT 1 FROM " + ACCOUNT_TABLE + " WHERE " + COLUMN_USERNAME + " = ?";
Cursor c = db.rawQuery(queryString, new String[]{user});
boolean result = c.getCount() > 0;
c.close();
db.close();
return result;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句