How does prepared statement skip the escape characters?

Viewed 143

I have a query like this

   val ps = con.prepareStatement(s"SELECT * from employee where name LIKE ?")
    ps.setString(1, "%" + searchTerm + "%")
    val rs = ps.executeQuery()

and when I print the prepared statement, I get

:HikariProxyPreparedStatement@710925960 wrapping com.mysql.cj.jdbc.ClientPreparedStatement: SELECT * from employee where name LIKE '%abc''%'

If i run the SELECT query in the mysql editor, I get error because the query is malformed. But when I run the prepared statement, I don't get error. Why is that ?

What query does prepared statement run, if the above query gives error? I see an empty result set, which means the query did not fail. Does the prepared statement change the query by itself ?

1 Answers

When you use a prepared statement, the values of parameters are not combined with the query until after it is parsed. So there's no way any special characters in the parameter value can upset the syntax of the query.

Related