SQLite:转义特殊字符 [英] SQLite: Escaping Special Characters

查看:64
本文介绍了SQLite:转义特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android中是否存在一种通用方法来转义SQLite数据库中不允许的所有字符?例如,"You \'Me'".而不是让我弄清楚不允许使用的每个字符,然后创建一堆或替换语句.我正在寻找类似以下的内容.

Is there a common way within Android to escape all of the characters that aren't allowed in a SQLite database? For instance, "You\'Me'". Instead of me figuring out every single character that has isn't allowed and creating a bunch or replace statements. I'm looking for something like the following.

value = SQLite.escapeString(value);
ContentValues contentValues = new ContentValues();
contentValues.put("name", value);
getContentResolver().insert(CONTENT_URI, contentValues);

//Retrieve data
Cursor cursor = getContentResolver().query(CONTENT_URI, null, "name=?", new String[]{SQLite.escapeString(value)}, null);
value = SQLite.unescapeString(cursor.getString(cursor.getColumnIndex("name"));

这是一厢情愿还是已经有解决方案?

Is this wishful thinking or is there something out there already that solves this?

更新

上面的代码有效,但是在不能使用?的情况下.运算符,您仍然需要某种方式来转义所有字符.例如:

The code above works but in the situations where you can't use the ? operator you still need some way for escaping all of the characters. For instance:

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_CATEGORY + " TEXT DEFAULT Misc.);");

此示例中的.将引发异常以及其他几个字符.是否有逃避所有这些字符的通用方法/方式?

The . in this example will throw an exception along with several other characters. Is there a common method/way to escape all of these characters?

推荐答案

在SQL中,字符串用'单引号'分隔.要在字符串中使用一个,必须将其加倍.

In SQL, strings are delimited with 'single quotes'. To use one inside a string, you have to double it.

在SQL中不需要转义其他字符.(如果要在另一种语言(例如Java)中嵌入字符串,则还必须使用该语言的转义机制.)

There are no other characters that need to be escaped in SQL. (If you're embedding strings in another language, such as Java, you also have to use the escape mechanisms of that language.)

为避免字符串格式问题,应改为使用参数:

To avoid string formatting problems, you should use parameters instead:

String name = "me";
db.rawQuery("SELECT ... WHERE name = ?", new String[]{ name });

这篇关于SQLite:转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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