如何在Android逃脱SQLite中不支持的字符? [英] How to escape unsupported character in SQLite on Android?

查看:310
本文介绍了如何在Android逃脱SQLite中不支持的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人可以告诉如何逃避或更换不支持的字符如单引号源码android的任何人可以举个例子

can anybody tell How to escape or replace not supported character like single quotes in sqlite in android can anybody give example

感谢

推荐答案

您可以利用公郎应用工具,也可以使用正则表达式来处理它。

You can utilize the commons-lang utility or you can use a regexp to handle it.

如果你正在构建动态SQL,我的建议是试图用一个prepared声明,将不再需要逃逸单引号。

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.

使用使用字符串连接刚刚建成一个动态的SQL语句:

Using just a dynamic SQL built using string concatenation:

String value = "one's self";
StringBuilder query= new StringBuilder();
query.append("insert into tname(foo) values (").append(value).append(")");
... execute call with query.toString() ...

修改成

String value = "one's self";
value= DatabaseUtils.sqlEscapeString(value);
StringBuilder query= new StringBuilder();
query.append("insert into tname(foo) values (").append(value).append(")");
... execute call with query.toString() ...

在理想情况下,用prepared声明

Ideally, use a prepared statement

String value = "one's self";
StringBuilder query= StringBuilder();
query.append("insert into tname(foo) values (?)");
SQLiteStatement stmt= db.compileStatement(query.toString());
stmt.bindString(1, value);
long rowId= stmt.executeInsert();
// do logic check for > -1 on success

这样你就不会遇到SQL注入攻击。

This way you don't run into "SQL injection attacks".

请参照<一个href="http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html">http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html了解更多信息。

修改 我没多一点挖,你可以使用<一个href="http://developer.android.com/reference/android/database/DatabaseUtils.html#sqlEscapeString%28java.lang.String%29">DatabaseUtils.sqlEscapeString(String)逃脱一个字符串的内容,所以它是有效的,没有prepares一个完整的SQL语句。

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.

这篇关于如何在Android逃脱SQLite中不支持的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆