查询联系电话时出现以下sqlite异常:
05-05 04:25:47.276: E/AndroidRuntime(7369): android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling:
SELECT data1, data2 FROM view_data_restricted data WHERE (1 AND mimetype = 'vnd.android.cursor.item/phone_v2') AND ( DISPLAY_NAME = 'Seller's Permit Rose Agent')
05-05 04:25:47.276: E/AndroidRuntime(7369): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:158)
05-05 04:25:47.276: E/AndroidRuntime(7369): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:114)
05-05 04:25:47.276: E/AndroidRuntime(7369): at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
05-05 04:25:47.276: E/AndroidRuntime(7369): at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
05-05 04:25:47.276: E/AndroidRuntime(7369): at android.content.ContentResolver.query(ContentResolver.java:245)
我对sqlite一无所知,因为我甚至没有直接使用它。我正在使用游标。异常的根是行:
phoneCursor = contentResolver.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.TYPE },
" DISPLAY_NAME = '" + name + "'", null, null);
完整的方法是
public ArrayList<Contact> getContacts() {
ArrayList<Contact> data = new ArrayList<Contact>();
contactCursor = contentResolver.query(Contacts.CONTENT_URI, new String[] { Contacts.DISPLAY_NAME, BaseColumns._ID }, null, null, null);
if (contactCursor != null) {
String name = null;
String phoneString = null;
long phoneNumber = -1;
long id;
InputStream image = null;
while (contactCursor.moveToNext()) {
name = contactCursor.getString(contactCursor.getColumnIndex(Contacts.DISPLAY_NAME));
image = Contacts.openContactPhotoInputStream(contentResolver, ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactCursor.getLong(contactCursor.getColumnIndex(BaseColumns._ID))));
id = contactCursor.getLong(contactCursor.getColumnIndex(BaseColumns._ID));
phoneCursor = contentResolver.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.TYPE },
" DISPLAY_NAME = '" + name + "'", null, null);
while (phoneCursor.moveToNext()) {
...
}
}
}
return data;
}
答案 0 :(得分:2)
android.database.sqlite.SQLiteException:near“s”:语法错误:,同时编译: SELECT data1,data2 FROM view_data_restricted data WHERE(1 AND mimetype ='vnd.android.cursor.item / phone_v2')AND(DISPLAY_NAME ='卖方许可玫瑰代理')
由于显示名称中的单引号而发生异常
试试这个
name=name.replace("'","''");
然后
phoneCursor = contentResolver.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.TYPE },
" DISPLAY_NAME = '" + name + "'", null, null);
答案 1 :(得分:1)
由于name
字符串中的单引号。一种方法是摆脱单引号,但这不是正确的方法。如果您希望代码在单引号和双引号中工作,请尝试使用rawQuery()而不是使用.query()方法。请参阅以上2个主题:Android quotes within an sql query string和handeling querying an item with a single quote in it。他们处理同样的问题。
答案 2 :(得分:0)
理想情况下应该这样做,
phoneCursor = contentResolver.query(Phone.CONTENT_URI, new String[] { Phone.NUMBER, Phone.TYPE }, " DISPLAY_NAME = ?", new String[] {name}, null);