stevebot
stevebot

Reputation: 24005

What characters will PreparedStatement escape?

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?

Upvotes: 6

Views: 11599

Answers (2)

ghostk
ghostk

Reputation: 11

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();

Upvotes: 1

axtavt
axtavt

Reputation: 242686

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).

Upvotes: 8

Related Questions