0

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?

2
  • 4
    Use Prepared Statements to solve that automatically. Commented Dec 6, 2013 at 7:47
  • Also it's always good to mention the actual DBMS you are using (Oracle, Postgres, ...) Commented Dec 6, 2013 at 7:49

2 Answers 2

3

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:

Exploits of a mom

Source

Sign up to request clarification or add additional context in comments.

Comments

0

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

Please note that since commons 3.0 StringEscapeUtils.escapeSql(str) is no longer supported.
I certainly wouldn't recommend it over a PreparedStatement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.