如何使用SQL查询转义用户提供的参数? [英] How to escape user-supplied parameters with a SQL query?

查看:263
本文介绍了如何使用SQL查询转义用户提供的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

使用准备好的陈述

例如:

con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");
pstmt.setInt(2, 100);
pstmt.setString(1, "Bob");
pstmt.executeUpdate();

它会阻止原始SQL注入

It will prevent raw SQL injection

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

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

另见

  • does-using-preparedstatement-mean-there-will-not-be-any-sql-injection

这篇关于如何使用SQL查询转义用户提供的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆