Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape quotes "" characters in MySQL and Java

Tags:

java

mysql

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

An incoming XML file has quotes, and I am parsing through that file using Java. So I want to escape the quotes here, but in the database it should contain quotes. When I am doing a query the result would have quotes. While displaying on a webpage it should also show quotes.

like image 632
Rachel Avatar asked Dec 10 '09 01:12

Rachel


People also ask

How do I escape a quote in MySQL?

To insert binary data into a string column (such as a BLOB column), you should represent certain characters by escape sequences. Backslash ( \ ) and the quote character used to quote the string must be escaped.

Which character is the escape character for MySQL?

MySQL recognizes the following escape sequences. \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character.

How do I escape a character in SQL?

In ANSI SQL, the backslash character (\) is the escape character. To search for data that begins with the string \abc , the WHERE clause must use an escape character as follows: ... where col1 = '\\abc';

How do I change the escape character in MySQL?

use this: SELECT REPLACE("abcdefgh\\i","\\", "adfc" ); single escape character will automatically escape character, so you need to put double escape character for remove escape character.


1 Answers

Let me try and understand...

The 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 database implementations (I'm thinking of you, Oracle >))

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

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

like image 171
PSpeed Avatar answered Sep 22 '22 08:09

PSpeed