简体   繁体   English

如何在Java中构建查询以防止使用预准备语句进行SQL注入

[英]How to build query in Java to prevent SQL injection using prepared statement

I need to build a query in such a way as to prevent the possibility of an SQL injection attack. 我需要以防止SQL注入攻击的可能性的方式构建查询。

I know of two ways to build a query. 我知道构建查询的两种方法。

String query = new StringBuilder("select * from tbl_names where name = '").append(name).append(';).toString();

String query = "select * from tbl_names where name = ? ";

In the first case, all I do is a connection.preparestatement(query) 在第一种情况下,我所做的只是一个connection.preparestatement(查询)

In the second case I do something like: 在第二种情况下,我做了类似的事情:

PreparedStatement ps = connection.prepareStatement(query)
ps.setString(1,name);

I want to know what is the industry standard? 我想知道什么是行业标准? Do you use the string append way to build the query and then prepare the statement or prepare the statement already and pass parameters later? 您是否使用字符串追加方式来构建查询,然后准备语句或准备语句并稍后传递参数?

Your first fragment of code is unsafe and vulnerable to SQL injection. 您的第一个代码片段不安全,容易受到SQL注入攻击。 You should not use that form. 你不应该使用那个表格。

To make your first fragment safe, you would need to manually escape the value to prevent SQL injection. 要使第一个片段安全,您需要手动转义该值以防止SQL注入。 That is hard to do correctly, and choosing the wrong way of handling values could potentially reduce performance depending on the underlying database (eg some database systems will not use an index if you supply a string literal for an integer column). 这很难正确执行,并且选择错误的处理值的方式可能会降低性能,具体取决于底层数据库(例如,如果为整数列提供字符串文字,某些数据库系统将不会使用索引)。

The second fragment is the standard way. 第二个片段是标准方式。 It protects you against SQL injection. 它可以保护您免受SQL注入。 Use this form. 使用此表单。

Using a prepared statement with parameter placeholders is far simpler, and it also allows you to reuse the compiled statement with different sets of values. 使用带参数占位符的预准备语句要简单得多,它还允许您使用不同的值集重用已编译的语句。 In addition, depending on the database, this can have additional performance advantages for reusing query plans across connections. 此外,根据数据库的不同,这可以为跨连接重用查询计划提供额外的性能优势。

You could also use the [OWASP ESAPI library][1] . 您也可以使用[OWASP ESAPI library][1] It includes validators, encoders and many other helpful things. 它包括验证器,编码器和许多其他有用的东西。 For example, you can do 例如,你可以做到

ESAPI.encoder().encodeForSQL(Codec,input);

More codecs are under development. 正在开发更多编解码器。 Currently, MySQL and Oracle are supported. 目前,支持MySQL和Oracle。 One of those might be helpful in your case. 其中一个可能对您的情况有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM