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);
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 ?
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).
Do not concatenate the
sqlString by+. You can useThis is slower than concatenating a String so you should initialize this
staticthen this is not a problem.I think using a
StringBuilderwill 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.