2012-03-01 33 views
0

我有以下的DML SQL(由mysql WB生成):逃逸报价为字段的值崩溃我的SQL脚本

INSERT INTO `status_need` VALUES (1,1,1,'famille cherchant une autre famille (pour garde partagée ou sortie d\'école)'),(2,1,2,'famille cherchant professionnelle de la garde d\'enfants'),(3,2,1,'professionnelle de la garde d\'enfants cherchant enfants à garder'); 

当我从Java运行它,它可能引发因错误撇号/报价在该字段的值内。

我不知道为什么这是因为引号被反斜线转义了,更重要的是,这个SQL是由mysql本身生成的。

任何人都可以请让我知道如何解决这个问题?

+0

谢谢大家的回复。我使用Unitils,所以我无法控制脚本的调用方式 - 例如使用PreparedStatements。 – balteo 2012-03-01 19:58:28

回答

1

我猜你的Java代码中有一个字符串字面看起来像这样:

"INSERT INTO `status_need` VALU...ie d\'écol..." 

不起作用的原因是在Java中,在字符串文字中,\'意味着'。你需要通过写\\,而不是逃避反斜杠\

"INSERT INTO `status_need` VALU...ie d\\'écol..." 

(或如danihp说,你可以通过编写'',而不是\'回避这个问题:MySQL支持逃逸内单引号的两种方式单引号字符串。)

+0

我希望我可以控制转义字符,但Mysql Workbench管理员似乎不允许这样做。 – balteo 2012-03-01 20:00:16

1

报价mysql文档:

There are several ways to include quote characters within a string: 

A “'” inside a string quoted with “'” may be written as “''”. 

A “"” inside a string quoted with “"” may be written as “""”. 

Precede the quote character by an escape character (“\”). 

A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment. 

正确答案是,你应该寻找一种方式,让java的这个给你。有点像real_escape php函数。请参阅:http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html