ResultSet fields cannot be accessed with a 0 index
44
45 URI offerAPI = new URI(req.getParameter("offerAPI"));
46
47 String id = r.getString(0); 48
49 if (r.getBoolean("isWin") && b) {
50 resp.getWriter().print("You win, " + r.getString("userName") + "!<br>You can fill your details in with this link: " + req.getParameter(id));
Description
A call to a getXXX
or updateXXX
method of a result set was made where the field index is 0
. As ResultSet
fields start at index 1
, this is always a mistake.
Using a 0 index with ResultSet
's getter and update methods will only trigger an SQLException
.
Bad Practice
Connection c = DriverManager.getConnection(...);
Statement s = conn.createStatement();
s.execute("SELECT userName, isWin FROM users WHERE uid = 'someuser';");
ResultSet r = s.getResultSet();
String userName = r.getString(0); // This will fail.
Recommended
String userName = r.getString(1);
Consider using column names instead of indices to avoid such mistakes in the future. Another possible way to mitigate this issue would be to have integer constants labelled with the respective column names.
int USER = 1;
String userName = r.getString(USER);
// Or:
String userName1 = r.getString("user");
References
- Spotbugs - SQL_BAD_RESULTSET_ACCESS