Sunday, March 27, 2011

PreparedStatements escape their arguments.



String sql = "select * from myTable where sometext=?";


PreparedStatement prep;


...


prep.setString(1, "I'm in yur SQL");


out.println(prep.toString());

>select * from myTable where sometext='I\'m in yur SQL'


I was 'pre-escaping' the 'sometext' string before hand, which means a 'double' escaping happens, causing the query to break.


I originally thought it magically stored the string and I didn't need escaping at all, but I messed up another part of the query, leading me down the wrong path. Argh!


Pro-tip, use TOAD, or similar tool (MySQL Workbench) to verify your queries.  The preparedStatement.toString() will spit out the query for you.



No comments:

Post a Comment