因此,在我学习 Android 的过程中,我得到了很多关于如何使用 ContentProvider
以及如何使用 SqliteDatabase
正确插入内容的建议。现在我有一个毫无意义的错误,至少对于每个人都告诉我的一切。错误是这样的:
android.database.sqlite.SQLiteException: near "s": syntax error:
while compiling: SELECT * FROM events WHERE time_stamp='07/21/2012 2:59:03 PM' AND
event='Test This's'
只要 '
没有出现在任何地方,一切都正常。我知道为什么,因为它需要转义。但这没有意义,因为每个人都告诉我不要使用原始查询,而是使用提供的绑定(bind)方法,如果这有意义的话。让我提供我的例子是什么:
ContentValues newValues = new ContentValues();
newValues.put("event_id", eventId);
newValues.put("event_name", eventName);
newValues.put("start_date", startDate);
newValues.put("start_time", values.getAsString("start_time"));
newValues.put("end_date", endDate);
newValues.put("end_time", values.getAsString("end_time"));
newValues.put("location", values.getAsString("location"));
Long success = database.insert("events_info", null, newValues);
据我所知,为什么我需要逃避它,因为它应该绑定(bind)它!?除非这仅适用于其他方法,如 query()
和 update()
。无论哪种情况,我都希望有人能够阐明在 Android 中为 SQLite 插入准备字符串的正确做法。提前谢谢你。
最佳答案
SELECT * FROM events WHERE time_stamp='07/21/2012 2:59:03 PM' AND event='Test This'
我想你知道,日期字符串 '07/21/2012 2:59:03 PM'
被正确分隔,事件字符串 'Test This's'
不是。
简单的修复方法是将字符串更改为 'Test This''
一般性问题,“您如何更正和验证输入”,实际上是一个非常大的问题 - 涉及的问题不仅仅是“引号”定界符。
可以说您的最佳防线是使用“查询参数”:
EXAMPLE:
p_query = "select * from mytable where name_field = ?";
mDb.rawQuery(p_query, new String[] { uvalue });
我很难找到关于该主题的好教程 - 抱歉。这是我能做的最好的事情:
这是一篇关于相关主题“SQL 注入(inject)”的好文章:
最后,如果你真的想“转义”你的输入字符串,你可以做得比使用简单的 Java String.replaceAll() 更糟糕:
关于android - 如何在 Android 中正确准备用于 SQLite 插入的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595129/