简体   繁体   English

在MySQL查询Java中使用撇号

[英]Using apostrophes in a MySQL query Java

so I have run into a bit of an Issue with MySQL. 所以我遇到了MySQL问题。 I have a service that allows administrators to ban users, and give a reason for their banning. 我有一项允许管理员禁止用户并提供禁止原因的服务。 This service is written fully in java... while I could use a PhP server and use the MySQL functionality in that to solve this... I feel I want to keep all of my MySQL functionality in one enviroment. 这项服务完全用Java编写...虽然我可以使用PhP服务器并使用MySQL功能来解决此问题...我觉得我想将所有MySQL功能都保留在一个环境中。

The issue comes about with the ability to give a reason, often an admin will give a reason something along the lines of "You're banned for: Griefing Bob's castle" (or something of the sort). 问题在于提供原因的能力,通常管理员会根据“您被禁止:给鲍勃的城堡发牢骚”之类的东西给出原因(或类似的东西)。 As noticed, the ' ' cause problems, because those are used to represent Strings in MySQL. 如前所述,“”会引起问题,因为这些问题用于表示MySQL中的字符串。

Are there any solutions in a Java environment? Java环境中是否有解决方案?

The easiest solution might be Commons Lang StringEscapeUtils.escapeSql(String) . 最简单的解决方案可能是Commons Lang StringEscapeUtils.escapeSql(String) Another solution is to use a PreparedStatement and to bind the parameters (some prefer this second option because it usually scales better and has faster performance). 另一个解决方案是使用PreparedStatement并绑定参数(有些人更喜欢第二个选项,因为它通常可以更好地扩展并且具有更快的性能)。

// From the JavaDoc on PreparedStatement
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES "
                                 + "SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM