如何转义 Android 上 SQLite 中不支持的字符?
任何人都可以告诉如何转义或替换不支持的字符,例如android中sqlite中的单引号任何人都可以举个例子
谢谢
can anybody tell How to escape or replace not supported character like single quotes in sqlite in android can anybody give example
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 commons-lang 实用程序,也可以使用正则表达式来处理它。
如果您正在构建动态 SQL,我建议尝试使用准备好的语句,这样就无需转义单引号。
仅使用使用字符串连接构建的动态 SQL:
将其更改为
理想情况下,使用准备好的语句
这样您就不会遇到“SQL 注入攻击”。
请参阅 http://developer.android.com/reference/android/database /sqlite/SQLiteStatement.html 了解更多信息。
编辑
我做了更多挖掘,您可以使用 DatabaseUtils.sqlEscapeString(String) 转义字符串的内容,使其对于没有准备的完整 SQL 语句有效。
You can utilize the commons-lang utility or you can use a regexp to handle it.
If you're building dynamic SQL, what I would suggest is trying to use a prepared statement which would eliminate the need for escaping single quotes.
Using just a dynamic SQL built using string concatenation:
Change that to
Ideally, use a prepared statement
This way you don't run into "SQL injection attacks".
Refer to http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html for more information.
EDIT
I did a little more digging, you can use DatabaseUtils.sqlEscapeString(String) to escape the content of a string so that it is valid for a complete SQL statement with no prepares.
这些不是用一个简单的\完成的吗?因此,您的单引号将是 \'。
Aren't these done with a simple \? So, your single quote would be \'.
实际上,最简单的方法是将单引号(')替换为两个单引号('')。然后你的查询将变成:
解释:SQLite提倡使用单引号(')而不是双引号(“)作为字符串分隔符,声称这是SQL标准所要求的(我无法 证实这一说法)。
SQLite 也与我所知道的所有其他 SQL 数据库不同,它使用 '' 而不是 \' ,再次声明 SQL 标准(我个人无法 与那个声称,因为我知道的所有其他 SQL 数据库都使用转义字符、反斜杠的 C 方式,即使它被编写为在 ISO 的 SQL 标准中的某处使用 '',我相信最好修改该标准以使用 C 方式,因为在实践中,它已经是标准了。
请注意:
是该逻辑的有效 sql 语句,并且不需要额外的转义。
Actually, the simpliest way is to replace single quotes (') with two-single quotes (''). Your query will then become:
Explanation: SQLite advocates the use of single quotes (') instead of double quotes (") as string delimiters, claiming that this is what the SQL standard requires (I was unable to confirm this). SQLite also differs from all other SQL databases I know, in that it uses '' instead of \' , again, claiming SQL standards. (Again, I was unable to confirm this claim).
Personally, I tend to disagree with that claim, since every other SQL database I know uses the C way of escaping chars, backslash. Even if it was written to use '' somewhere in ISO's SQL standard, I believe it might be best to revise that standard to use the C way, because in practice, it already is the standard anyway.
Please note that:
is a valid sql statement by that logic, and requires no additional escaping.