如何在源码中的Andr​​oid逃避特殊字符,如“ [英] How to escape special characters like ' in sqlite in android

查看:371
本文介绍了如何在源码中的Andr​​oid逃避特殊字符,如“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这是在SQLite数据库表执行查询的功能。我宣布一个恒定的:公共静态最后弦乐CANADA_HISTORY =加拿大的历史; 。它被保存在一个字符串变量假设困难

I have a function which is executing a query on a table in SQLite database. I declare a constant: public static final String CANADA_HISTORY = "Canada's History";. This is stored in a String variable let's say difficulty,

我有一个查询:

Cursor c = mDb.rawQuery("select * from Questions_answers where CHAPTERS = '"+difficulty+"'" , null);

这是抛出一个异常,附近的撇号。

It is throwing an exception near the apostrophe.

logcat的输出:

Logcat output:

I/Database( 1170): sqlite returned: error code = 1, msg = near "s": syntax error
D/AndroidRuntime( 1170): Shutting down VM
W/dalvikvm( 1170): threadid=1: thread exiting with uncaught exception (group=0x40015560)
E/AndroidRuntime( 1170): FATAL EXCEPTION: main
E/AndroidRuntime( 1170): android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling: select * from Questions_answers where CHAPTERS  = 'Canada's History'

我也曾尝试:

I have also tried:

1.  difficulty=difficulty.replaceAll("'","''");
2.  difficulty=difficulty.replaceAll("'","\'");
3.  difficulty = DatabaseUtils.sqlEscapeString(difficulty);

要补充,它的工作我要在单个词如加拿大历史,我的意思是没有的特殊字符字。

To add to that, it's working me for the single words like Canada History, I mean without the special character word.

请给我建议的解决问题,谢谢。

Please give me advice for the solve problem Thanks.

推荐答案

先用这个替代字符

difficulty=difficulty.replaceAll("'","\'");

然后通过它查询

then pass it in your query

"select * from Questions_answers where CHAPTERS='"+difficulty+"'";

编辑:

 q = "select * from Questions_answers where CHAPTERS = ?";
    database.rawQuery(q, new String[] { difficulty});

这篇关于如何在源码中的Andr​​oid逃避特殊字符,如“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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