Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What characters will PreparedStatement escape?

Tags:

java

jdbc

I noticed that when I use a PreparedStatement it doesn't seem to escape certain wild-card characters like '%' or '_'. I know these can be escaped in MySql using a backslash. This made me wonder, what characters will a PreparedStatement escape?

like image 552
stevebot Avatar asked Oct 14 '10 15:10

stevebot


People also ask

What character is used to escape strings?

An escape sequence contains a backslash (\) symbol followed by one of the escape sequence characters or an octal or hexadecimal number. A hexadecimal escape sequence contains an x followed by one or more hexadecimal digits (0-9, A-F, a-f). An octal escape sequence uses up to three octal digits (0-7).

What is escape character example?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do you escape characters?

Use the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.

What is \u escape character?

A unicode escape sequence is a backslash followed by the letter 'u' followed by four hexadecimal digits (0-9a-fA-F). It matches a character in the target sequence with the value specified by the four digits. For example, ”\u0041“ matches the target sequence ”A“ when the ASCII character encoding is used.


2 Answers

PreparedStatement doesn't escape anything - it relies on database support for precompiled statements.

That is, PreparedStatement never substitutes ?s for parameter values in order to form a literal query string. Instead, it sends a query string with placeholders to the database and uses database support to bind query parameters (however, it may depend on JDBC driver implementation).

like image 188
axtavt Avatar answered Oct 28 '22 23:10

axtavt


In my test, it escapes single quotation marks, \r, \t, \n and so forth. It works pretty nice:

String sql = "INSERT INTO test(title) VALUES(?)";
PreparedStatement stmt = con.prepareStatement(sql);
String title = "I'm a \"student\" in a \t (university) \r\n";
stmt.setString(1, title);
stmt.executeUpdate();
like image 21
ghostk Avatar answered Oct 29 '22 00:10

ghostk