views:

898

answers:

6

I'm still somewhat new to Java and trying to insert data into a database. I'm getting an error when inserting a string containing 's so my end result would be to escape the apostrophe. How can I accomplish?

A: 

That's dependent on the database you are using. Usually '' works (I only have firsthand knowledge with SQL Server).

What database are you using?

Chris Kaminski
I'm using mysql
Jonathan Kushner
+2  A: 

Depends on the database, but you can use '' in SqlServer.

EDIT: In MySql you can use a double apostrophe or backslash: http://www.faqts.com/knowledge_base/view.phtml/aid/630

Michael Todd
Double apostrophe in postgres
Ewan Todd
And I'll agree with James in comment: use prepared statements. Much better long-term solution.
Michael Todd
+11  A: 

Use prepared statements. As well as handling any special characters, they are much more robust and help prevent sql injection attacks.

james
+1 This answer gets to the heart of the issue: hand-coding your own SQL in your method calls is bad practice, and opens you up to a host of security issues.
rtperson
A good habit to get into, but perhaps overkill for learning the language.
Chris Kaminski
... just ask Little Bobby Tables. :)
rtperson
+1 for XKCD reference http://xkcd.com/327/
Chris Nava
+5  A: 

The issue really isn't with Java, rather with the underlying database. Most likely you are stringing your parameters together like this:

  String sql = "select * from sometable where somefield = " + someObject.getSomeField();

Don't do that. Use PreparedStatement's instead.

That has the added advantage of preventing SQL injection attacks, if this is an application that has to be concerned about such things.

Yishai
+1: it not only saves you from SQL injection attacks, but it also eases setting Java objects inside a SQL statement (Date, InputStream, etc) and is technically also more performant (precompiled at DB).
BalusC
+1  A: 

I assume you are using a java.sql.Statement, and calling the executeQuery method with a String. That's bad, because it's possible to do SQL injection. You should use a java.sql.PreparedStatement instead, and then you can set any String that you want as a parameter, and you won't have your problem.

For example:

PreparedStatement pstmt = con.prepareStatement("UPDATE MY_TABLE SET TEXT_FIELD = ?");
pstmt.setString(1, "any String 'will work here!");
Kaleb Brasee
+2  A: 

Using StringEscapeUtils:

StringEscapeUtils.escapeSql(yourstring);
RHSeeger
That's exactly what I was looking for.
Jonathan Kushner