How to escape user-supplied parameters with a SQL

2019-01-27 19:58发布

问题:

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?

回答1:

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