简体   繁体   English

使用正则表达式在Java字符串中转义文字

[英]escaping literal's in java string using regex

i have a string value that i have to insert in mysql database. 我有一个字符串值,我必须在mysql数据库中插入。 and i have to escape some literal like (' , " ,% ,) in this string so how can i use regex for that 而且我必须在此字符串中转义一些文字(',“,%,),所以我该如何使用正则表达式

Don't use regex. 不要使用正则表达式。 Use a database library that escapes things for you, and let it handle this. 使用一个可以为您进行转义的数据库库,并由它来处理。

Don't try to do this yourself. 不要尝试自己做。 Let the JDBC driver handle it, by using PreparedStatement instead of concatenating an SQL statement using strings yourself. 让JDBC驱动程序通过使用PreparedStatement来处理它,而不是自己使用字符串来连接SQL语句。 Example: 例:

Connection conn = ...;    // Database connection

PreparedStatement ps = conn.prepareStatement("INSERT INTO MYTABLE (NAME, AGE) VALUES (?, ?)");

ps.setString(1, "Jesper");
ps.setInt(2, 38);

ps.executeUpdate();

If you use PreparedStatement , the JDBC driver will take care of escaping the inserted values correctly for whatever brand and version of the database that you use. 如果使用PreparedStatement ,则JDBC驱动程序将为您使用的任何品牌和版本的数据库正确地转义插入的值。

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

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