如何避免“安全性 - 从非常量字符串生成预准备语句” FindBugs警告 [英] How to avoid "Security - A prepared statement is generated from a nonconstant String" FindBugs Warning

查看:1620
本文介绍了如何避免“安全性 - 从非常量字符串生成预准备语句” FindBugs警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,其代码如下:

I am working on a project that has a piece of code like the one below:

String sql = "SELECT MAX(" + columnName + ") FROM " + tableName;                
PreparedStatement ps = connection.prepareStatement(sql);

我有什么方法可以更改此代码,以便FindBugs停止给我
安全 - 从非恒定的字符串准备好了一个声明?警告

Is there any way that I can change this code so that FindBugs stop giving me a "Security - A prepared statement is generated from a nonconstant String" warning ?

请假设这个代码是安全的有关SQL INJECTION因为我可以控制在尽可能代码的其他地方为 表名 和 COLUMNNAME(它们不直接从用户输入来)。

Please assume that this code is safe regarding SQL INJECTION since I can control elsewhere in the code the possible values for "tableName" and "columnName" (they do not come come directly from user input).

推荐答案


值不要通过 + 连接 sql 字符串。可以使用

Do not concatenate the sql String by +. You can use

String sql = String.format("SELECT MAX(%s) FROM %s ", columnName, tableName);

这比串联一个字符串慢,所以你应该初始化这个 static 那么这不是问题。

This is slower than concatenating a String so you should initialize this static then this is not a problem.

我认为使用 StringBuilder 也会修复此警告

I think using a StringBuilder will also fix this warning.

可以避免此警告的另一种方法是添加 @SuppressWarnings( SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING)该字符串上述(或者该方法/或类)。

Another way you can avoid this warning is to add @SuppressWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING") above that string (or the method/or the class).

您也使用过滤文件以定义应排除的规则。

You could also use a Filter File to define rules which should be excluded.

这篇关于如何避免“安全性 - 从非常量字符串生成预准备语句” FindBugs警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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