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?
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).
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.
Use the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With