How to escape user-supplied parameters with a SQL query?

蓝咒 提交于 2019-12-18 07:43:16

问题


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


来源:https://stackoverflow.com/questions/4954002/how-to-escape-user-supplied-parameters-with-a-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!