tags:

views:

430

answers:

5

How can we escape quotes "" characters in Java and MySQL?

Incoming xml file has quotes and am parsing through that file using java and so i want to escape quotes here but in database it should contain quotes and while am doing query the result would have quotes and while displaying on webpage also it should show quotes. Hope am making my self bit clear

+3  A: 

The typical escape character for pretty much anything is the backslash \.

Anon.
+1  A: 
\"

Required 15 characters

BioBuckyBall
+1  A: 

Anything (ok not anything) but most characters use

 \

as the escape character

Brendan
A: 

The obvious (and best) thing to do is what everyone else suggested. A goofy alternative is to put the double quote inside a single quote:

String quotedText = '"' + "A quick brown fox..." + '"';
Suppressingfire
+1  A: 

Let me try and understand...

Incoming file has quotes in it. You want to send it to a database. When you get it back from the database then you still want those quotes to be there.

So is it just to/from the database that you are having your issue?

If so then I highly suspect you are doing something on the order of: (I'm wrapping it in a disclaimer to keep the unsuspecting from misunderstanding and cutting/pasting into their own applications. ;))

BAD DO NOT DO THIS

String sql = "insert into foo (bar,baz) values(" +myValue1 + ", " + myValue2 + ")";
Statement stmt = connection.createStatement();
stmt.executeUpdate( sql );

BAD DO NOT DO THAT

If so then you should really be using prepared statement's parameters at a minimum. a) you will be less vulnerable to malicious garbage deleting all of your tables, and b) you will not have any escaping problems.

String sql = "insert into foo (bar, baz) values( ?, ? )";
PreparedStatement stmt = connection.prepareStatement( sql );
stmt.setString( 1, myValue1 );
stmt.setString( 2, myValue2 );
stmt.executeUpdate();

Note that it's also safer in the case of things like CLOBs and the specifics of different DB implementations (I'm thinking of you Oracle >))

If it is some other kind of escaping, ie: to/from XML or to/from HTML then that's different but well documented all over the web.

Or provide some example code if I'm totally off base.

PSpeed