How to avoid “Security - A prepared statement is generated from a nonconstant String” FindBugs Warning

前端 未结 7 2911
灰色年华
灰色年华 2021-02-19 21:39

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

String sql = \"SELECT MAX(\" + columnName + \") FROM \" + tableName;                
Prepa         


        
7条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 22:13

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

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

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

    I think using a StringBuilder will also fix this warning.

    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.

提交回复
热议问题