Question

Sonar complains about a method:

"A prepared statement is generated from a nonconstant String"

I understand, it is not safe to parameterize a query by string concatenation, but here I am defining the name of the table. How to get rid of the sonar warning? And more importantly, how to fix this issue, how to avoid sql injection? Should I start searching invalid values in db and node variables, eg. must not contain space or ; (the usual checked input stuff), or is there an elegant way?

Btw, the method is very deep in the app, I doubt there is a chance to force any value upon these parameters by the ui.

The simplified version of the method:

private PreparedStatement getPs(Connection conn, String db, String node, String ext) {
    StringBuilder sql = new StringBuilder("select name, sum(counter) cnt");
    sql.append(" from ").append(db).append(".").append(node).append("_stuff");
    sql.append(" where something = ?");
    sql.append(" group by name");

    PreparedStatement ps;
    try {
        ps = conn.prepareStatement(sql.toString());
        ps.setString(1, ext);
    } catch (SQLException sqle) {
        throw new MyRuntimeException(sqle);
    }
    return ps;
}

Thanks for any help.

Was it helpful?

Solution

The sonar warning tells precisely what it warns about:

"A prepared statement is generated from a nonconstant String"

That doesn't mean that your code is vulnerable to SQL injection attacks. That simply means that it could be. If you're absolutely sure that there is no way for a user to inject a database schema or table name, then simply ignore the warning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top