FindBugs seems to have problems with the comma in the string build by the stringbuilder. See code below
sb.append("INSERT INTO ");
sb.append(DBConstants.SESSION_TB + " (");
// FindBugs complains
// sb.append(DBConstants.SESSION_ID + ", ");
// no complains (but wrong sql syntax i know)
sb.append(DBConstants.SESSION_ID + " ");
sb.append(DBConstants.SESSION_DATE + ") ");
sb.append("VALUES (?,?)");
String id = UUID.randomUUID().toString();
Date now = new Date();
statement = con.prepareStatement(sb.toString());
statement.setString(1, id);
statement.setTimestamp(2, new java.sql.Timestamp(now.getTime()));
statement.executeUpdate();
Please show how DBConstants.SESSION_ID is declared. Is it compile-time constant?
DBConstants.SESSION_ID is a public static final field.
public class DBConstants {
public static final String SESSION_TB = "sessions";
public static final String SESSION_ID = SESSION_TB + ".id";
}
Currently I am working on a similar project and I do have the same problem there. I tried different methods to create the query:
1) with stringbuilder
2) with declaring a final String variable: final String query = new String(sb.toString());
3) using String.format ("INSERT INTO $1%s ($2%s, $3%s, ...) VALUES (?,?,...)", DBConstants.SESSION_TB, DBConstants.SESSION_ID, DBConstants.SESSION_DATE, ...);
4) Using a totally fixed and not concatenated string like final String query = "INSERT INTO sessions (sessions.id, sessions.date) VALUES (?,?)";
FindBugs complains about ALL 4 types. (warns about SQL Injection)
I can give you a more code, if you need.
Last edit: What the heck 2015-12-28
o.O Sorry to post again but found a weird "thing":
At the end, the String.format() method works like a charm. The fixed string too. I never deleted the stringbuilder lines for the testing so I thought, they would also not work.
Last edit: What the heck 2015-12-28
Thank you for the additional information. In general this detector is poorly written: it may trigger false-positive when you concatenate one string, then execute with another. Pull requests are welcome by the way!