简体   繁体   中英

escaping literal's in java string using regex

i have a string value that i have to insert in mysql database. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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