0

If I have a string that looks like this:

This is a string
with single quotes ' all over
the ' place as well as
return characters

How would I convert this to a string that can be used in an INSERT statement?

INSERT INTO MyTable VALUES ('<the above string>');

The string above has the problems that it has return characters as well as single quotes which would mess up the validity of the INSERT statement above.

Edit: Sorry I probably should have been more clear. I'm generating a SQL Script with INSERT statements, not executing SQL within a Java app.

0

4 Answers 4

2

I'm generating a SQL Script with INSERT statements, not executing SQL within a Java app.

In that case, you'll have to generate an "escaped" version of the String. To do so, I'd suggest using the ESAPI library from the OWASP project (if possible). See Defense Option 3: Escaping All User Supplied Input for more details.

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

Comments

2

Use PreparedStatement:

String sql = "INSERT INTO MyTable VALUES (?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, theAboveString);
ps.executeUpdate();

1 Comment

I'm not executing the SQL however. I'm intending on generating a SQL Script that has INSERT statements in it for someone else to execute.
0

To put a single quote inside of an SQL string, use it twice.

so

insert into mytable
values ('isn''t it lovely?')

So when generating the sql script, just replace all single quotes with double quotes before tacking the beginning and ending single quotes onto it.

Comments

0

why dont use escape the single quotes like below

This is a string with single quotes \' all over the \' place as well as return characters

Comments

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.