Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape single quote in string literal using MySQL from Java

Tags:

java

mysql

I have a MySql table person_details which contains p_id and p_name. Now, if I want to insert a record where p_name contains a single quote ', I'd execute it this way-

insert into person_details values (1, 'D\'souza');

Now, I'm trying to execute the same through a java code this way-

insert into person_details values (1, 'D\\\'souza');

and I get MySQLSyntaxErrorException.

Anything wrong?

like image 869
AlwaysALearner Avatar asked Mar 04 '13 09:03

AlwaysALearner


4 Answers

To answer your question directly, double the quotes.

insert into person_details values (1, 'D''souza');

But I rather parameterized the query using PreparedStatement.

Here are the PROs:

  • avoid from SQL Injection
  • doesn't need to use single quotes.

example,

String str = "insert into person_details values (?, ?)";
query = con.prepareStatement(str);
query.setInt(1, 1);
query.setString(2, "D'souza");
query.executeUpdate();
  • Using Prepared Statements
like image 112
John Woo Avatar answered Oct 19 '22 02:10

John Woo


In MySQL, you use '' for a single ' inside a string:

insert into person_details values (1, 'D''souza');

Link to docs

But that's only for when you're providing the data literally, such as an SQL script to pre-populate a table with data you control, etc. If you're receiving that string from an external source (an end user, for instance, or an external system) then presumably you won't be writing a literal, but rather using a string variable. In that case, you want to use prepared statements as JW. describes in his answer. Why: http://xkcd.com/327/

like image 37
T.J. Crowder Avatar answered Oct 19 '22 04:10

T.J. Crowder


You could also use "

insert into person_details values (1, "D'souza");
like image 42
Riho Avatar answered Oct 19 '22 03:10

Riho


Why dont you use PreparedStatements

It will also take care of SQL Injections

like image 34
rajesh Avatar answered Oct 19 '22 04:10

rajesh