The parameters in a PreparedStatement
are indexed beginning at 1, not 0, so using any "set" method of a PreparedStatement
with a number less than 1 is a bug, as is using an index higher than the number of parameters. The same indexing style also applies to
ResultSet
.
Noncompliant Code Example
PreparedStatement ps = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?");
ps.setDate(0, date); // Noncompliant
ps.setDouble(3, salary); // Noncompliant
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String fname = rs.getString(0); // Noncompliant
// ...
}
Compliant Solution
PreparedStatement ps = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?");
ps.setDate(1, date);
ps.setDouble(2, salary);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String fname = rs.getString(1);
// ...
}