I'm facing an issue with insertion to SQL database from java code. I'm using INSERT sql query using the java code to enter the data from XML file to SQL database. You may suppose column named "Description". Imagine there is a record in XML which contains apostrophe ('). The program crashes due to the error caused by the apostrophe which is included in the data. I know that manually we can add another apostrophe and make it work, but imagine data of 10.000 records, how can we handle this issue?
-
4Use Prepared Statements to solve that automatically.juergen d– juergen d2013-12-06 07:47:42 +00:00Commented Dec 6, 2013 at 7:47
-
Also it's always good to mention the actual DBMS you are using (Oracle, Postgres, ...)user330315– user3303152013-12-06 07:49:11 +00:00Commented Dec 6, 2013 at 7:49
Add a comment
|
2 Answers
Don't do this (string concatenation):
String sql = "insert into MyTable (description) values ('" + value + "')";
Statement st = connection.createStatement();
st.executeUpdate(sql);
Do do this (prepared statement):
PreparedStatement ps = connection.prepareStatement(
"insert into MyTable (description) values (?)"
);
ps.setString(1, value);
pt.executeUpdate();
The value will get correctly escaped for you. Not only does this protect against mishaps like the one you mentioned, it also helps defend you from SQL injection attacks.
Humorous illustration:

Comments
You have two options, you should use PreparedStatement and bind your parameter(s). Or, if you really, really, want - you could use StringEscapeUtils.escapeSql(str).
2 Comments
Jayamohan
Please note that since commons 3.0
StringEscapeUtils.escapeSql(str) is no longer supported.Elliott Frisch
I certainly wouldn't recommend it over a PreparedStatement.