如何使用 MySQL 从 Java 转义字符串文字中的单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15198580/
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
How to escape single quote in string literal using MySQL from Java
提问by AlwaysALearner
I have a MySql table person_details
which contains p_id
and p_name
. Now, if I want to insert a record where p_name contains a single quote '
, I'd execute it this way-
我有一个person_details
包含p_id
和的 MySql 表p_name
。现在,如果我想插入一条记录,其中 p_name 包含单引号'
,我会这样执行——
insert into person_details values (1, 'D\'souza');
insert into person_details values (1, 'D\'souza');
Now, I'm trying to execute the same through a java code this way-
现在,我试图通过这种方式通过 Java 代码执行相同的操作 -
insert into person_details values (1, 'D\\\'souza');
insert into person_details values (1, 'D\\\'souza');
and I get MySQLSyntaxErrorException.
我得到 MySQLSyntaxErrorException。
Anything wrong?
哪里不对了?
回答by John Woo
To answer your question directly, double the quotes.
要直接回答您的问题,请将引号加倍。
insert into person_details values (1, 'D''souza');
But I rather parameterized the query using PreparedStatement
.
但我宁愿使用PreparedStatement
.
Here are the PROs:
以下是 PRO:
- avoid from SQL Injection
- doesn't need to use single quotes.
- 避免 SQL 注入
- 不需要使用单引号。
example,
例子,
String str = "insert into person_details values (?, ?)";
query = con.prepareStatement(str);
query.setInt(1, 1);
query.setString(2, "D'souza");
query.executeUpdate();
回答by T.J. Crowder
In MySQL, you use ''
for a single '
inside a string:
在 MySQL 中,您在字符串中使用''
单个'
:
insert into person_details values (1, 'D''souza');
But that's only for when you're providing the data literally, such as an SQL script to pre-populate a table with data you control, etc. If you're receiving that string from an external source (an end user, for instance, or an external system) then presumably you won't be writing a literal, but rather using a string variable. In that case, you want to use prepared statements as JW. describes in his answer. Why: http://xkcd.com/327/
但这仅适用于您按字面提供数据时,例如使用您控制的数据预先填充表的 SQL 脚本等。如果您从外部源(例如,最终用户)接收该字符串,或外部系统)然后大概你不会写文字,而是使用字符串变量。在这种情况下,您希望将准备好的语句用作JW。在他的回答中描述。为什么:http: //xkcd.com/327/
回答by Riho
You could also use "
你也可以使用 "
insert into person_details values (1, "D'souza");
回答by rajesh
Why dont you use PreparedStatements
为什么不使用PreparedStatements
It will also take care of SQL Injections
它还将处理 SQL 注入