我正在学习android,所以我决定制作一个简单的短信应用程序。一切进展顺利,但我遇到了一个我认为我能够绕过的问题,但我仍然想知道为什么会发生这种情况。
我会尽量不用多余的代码来打扰您,但如果需要,我会编辑问题并发布更多内容。
结构:
我有一个类:
public class MyDatabaseHelper extends SQLiteOpenHelper
处理数据库操作。
其中,我有以下方法:
public Contact getContactFromPhoneNumber(String pn) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM "+CONTACT_TABLE_NAME+" WHERE "+CONTACT_PHONE_NUMBER+"="+pn+";";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
Contact contact = new Contact();
contact.setId(cursor.getInt(cursor.getColumnIndex(CONTACT_PRIMARY_KEY)));
contact.setFirstName(cursor.getString(cursor.getColumnIndex(CONTACT_FIRST_NAME)));
contact.setLastName(cursor.getString(cursor.getColumnIndex(CONTACT_LAST_NAME)));
contact.setPhoneNumber(cursor.getString(cursor.getColumnIndex(CONTACT_PHONE_NUMBER)));
db.close();
return contact;
}
db.close();
return null;
}
它根据电话号码返回 Contact
对象。
Contact 类是一个简单的类,具有属性 fistName
、 lastName
、 phoneNumber
和 id
的 getter 和 setter 方法。
我需要提及的另一件事:
我不将一些任意字符串值传递给该方法。我传递的值之前已插入到数据库中,如下所示:
public void insertContact(String fn, String ln, String pn) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(CONTACT_FIRST_NAME, fn);
cv.put(CONTACT_LAST_NAME, ln);
cv.put(CONTACT_PHONE_NUMBER, pn);
db.insert(CONTACT_TABLE_NAME, null, cv);
db.close();
}
所以我传递给第一个方法的参数已经在数据库中。
联系人表中存储电话号码的字段类型为 TEXT
。
问题:
问题在于,当使用某些以 0
开头或包含 +
字符(我需要 +
字符来表示国家/地区调用代码)的字符串值作为参数调用上述方法时,它会返回 null
。
如果 pn
参数不以 0
开头或包含 +
,则效果很好。
示例:(结果在评论中)
Contact c = getContactFromPhoneNumber("123456") // c != NULL
Contact c = getContactFromPhoneNumber("1023") // c != NULL
Contact c = getContactFromPhoneNumber("0123") // c = NULL
Contact c = getContactFromPhoneNumber("+3816035") // c = NULL
Contact c = getContactFromPhoneNumber("123+123") // c = NULL
知道为什么会发生这种情况吗?
最佳答案
您的数据存储为字符串,但这里选择查询...
String selectQuery = "SELECT * FROM "+CONTACT_TABLE_NAME+" WHERE "+CONTACT_PHONE_NUMBER+"="+pn+";";
... 不引用 pn
作为字符串文字。由于它可以被解释为数字,因此不存在语法错误,但它与前面带有 +
或 0
的任何字符串都不匹配。
要在 SQL 中引用字符串文字,请使用 ''
单引号。但是,最好使用 ?
占位符并在那里绑定(bind)值,例如
String selectQuery = "SELECT * FROM "+CONTACT_TABLE_NAME+" WHERE "+CONTACT_PHONE_NUMBER+"=?;";
Cursor cursor = db.rawQuery(selectQuery, new String[] { pn });
关于java - Android SQLite select语句奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406969/