java 如何使用 SQL 查询转义用户提供的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4954002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:46:28  来源:igfitidea点击:

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

javasecurityjdbcsql-injection

提问by user291701

Trying to get started with JDBC (using Jetty + MySQL). I'm not sure how to escape user-supplied parameters in a SQL statement. Example:

尝试开始使用 JDBC(使用 Jetty + MySQL)。我不确定如何在 SQL 语句中转义用户提供的参数。例子:

String username = getDangerousValueFromUser();
Statement stmt = conn.createStatement();
stmt.execute("some statement where username = '" + username + "'"));

How do we escape "username" before use with a statement?

我们如何在使用语句之前转义“用户名”?

回答by Jigar Joshi

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

它将防止原始 SQL 注入

If you want to escape sql string then check for StringEscapeUtils.escapeSql(). Note that that this method was deprecated in Commons Lang 3.

如果要转义 sql 字符串,请检查StringEscapeUtils.escapeSql(). 请注意,此方法在 Commons Lang 3 中已弃用

Also See

另见