tags:

views:

105

answers:

2

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
For instance... any JDBC driver with PreparedStatement or PreparedCall.
R. Bemrose
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
@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
Use the PreparedStatement class, the documentation is here:http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html
Brian Schroth
+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