Trying to get started with JDBC (using Jetty + MySQL). I'm not sure how to escape user-supplied parameters in a SQL statement. Example:
String username = getDangerousValueFromUser();
Statement stmt = conn.createStatement();
stmt.execute("some statement where username = '" + username + "'"));
How do we escape "username" before use with a statement?
Use Prepared statement.
for example :
con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");
pstmt.setInt(2, 100);
pstmt.setString(1, "Bob");
pstmt.executeUpdate();
It will prevent raw SQL injection
If you want to escape sql string then check for StringEscapeUtils.escapeSql()
. Note that that this method was deprecated in Commons Lang 3.
Also See
- does-using-preparedstatement-mean-there-will-not-be-any-sql-injection