如果通过电子邮件不存在,我尝试将行插入数据库:
public boolean AddUserIfNotExist(String email, String password, String username) {
SQLiteDatabase db = m_helper.getWritableDatabase();
//String Query = "INSERT OR IGNORE INTO USERS(email, password, username)
//values('" + email + "','" + password + "','" + username + "');";
String Query = "INSERT INTO USERS(email, password, username) " +
"SELECT '" + email + "','" + password + "','" + username + "' "
+ "WHERE NOT EXISTS(SELECT 1 FROM USERS WHERE email = '" + email + "');";
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0) {
return false;
}
return true;
}
为什么它不起作用? cursor.getCount始终返回false。
答案 0 :(得分:1)
INSERT语句不返回任何行,因此您无法使用rawQuery
;对于INSERT,您必须改为使用execSQL
。
如果要确定记录是否存在,只需单独执行(同样,使用参数以避免字符串格式化问题):
if (DatabaseUtils.queryNumEntries(db, "Users",
"email = ?", new String[] { email })) > 0) {
// probably UPDATE?
return true;
} else {
db.execSQL("INSERT INTO Users(email, password, username) VALUES(?,?,?)",
new Object[] { email, password, username });
return false;
}