sql查询字符串中的Android引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1296180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android quotes within an sql query string
提问by miannelle
I want to perform a query like the following:
我想执行如下查询:
uvalue = EditText( some user value );
p_query = "select * from mytable where name_field = '" + uvalue + "'" ;
mDb.rawQuery( p_query, null );
if the user enters a single quote in their input it crashes. If you change it to:
如果用户在输入中输入单引号,它会崩溃。如果将其更改为:
p_query = "select * from mytable where name_field = \"" + uvalue + "\"" ;
it crashes if the user enters a double quote in their input. and of course they could always enter both single and double quotes.
如果用户在输入中输入双引号,它会崩溃。当然,他们总是可以同时输入单引号和双引号。
回答by Josef Pfleger
You should make use of the rawQuery
method's selectionArgs
parameter:
您应该使用该rawQuery
方法的selectionArgs
参数:
p_query = "select * from mytable where name_field = ?";
mDb.rawQuery(p_query, new String[] { uvalue });
This not only solves your quotes problem but also mitigates SQL Injection
.
这不仅可以解决您的报价问题,还可以减轻SQL Injection
.
回答by Nikhil
DatabaseUtils.sqlEscapeString worked properly for me. The string is enclosed by single quotes and the single quotes inside the string become double quotes. Tried using selectionArgs in the getContentResolver().query() but it didn't work at all.
DatabaseUtils.sqlEscapeString 对我来说工作正常。字符串用单引号括起来,字符串内的单引号变成双引号。尝试在 getContentResolver().query() 中使用 selectionArgs 但它根本不起作用。
回答by Absar Alam
You should change
你应该改变
p_query = "select * from mytable where name_field = '" + uvalue + "'" ;
like
喜欢
p_query = "select * from mytable where name_field = '" + android.database.DatabaseUtils.sqlEscapeString(uvalue)+ "'" ;
回答by gssi
Have you tried replacing a single quote with 2 single quotes? That works for inputting data to a database.
您是否尝试用 2 个单引号替换单引号?这适用于将数据输入数据库。
回答by Amt87
I prefer to escape Single quotes and Double quotes in each insert statement with Sqlite like this:
我更喜欢使用 Sqlite 在每个插入语句中转义单引号和双引号,如下所示:
String sqlite_stament = sqlite_stament.replace("'", "''").replace("\"", "\"\"");
回答by Nency
I have same problem but now it is solved by just writing the code like in your case you want to insert value uvalue .Then write as
我有同样的问题,但现在只需编写代码即可解决,就像你想插入值 uvalue 一样。然后写为
uvalue= EditText( some user value );
uvalue = uvalue.replaceAll("'", "''");
p_query = "select * from mytable where name_field = '" + uvalue + "'" ;
mDb.rawQuery( p_query, null );
cool..!!
凉爽的..!!