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
+8
A:
Don't use regex. Use a database library that escapes things for you, and let it handle this.
Brian Schroth
2009-10-21 13:44:59
For instance... any JDBC driver with PreparedStatement or PreparedCall.
R. Bemrose
2009-10-21 13:45:36
so how can we use database library? and what i have done this thing before through perl using regex but now i want that thing in java before inserting record in database
lakhaman
2009-10-21 13:53:47
@lakhaman: Use prepared statements, and bind your (plain) string value as a parameter. Simple, and orders of magnitude more likely to be correct than trying to roll your own regex. See Jesper's answer for an example.
Andrzej Doyle
2009-10-21 14:05:30
Use the PreparedStatement class, the documentation is here:http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html
Brian Schroth
2009-10-21 14:13:19
+4
A:
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.
Jesper
2009-10-21 13:57:40