== Why is this an issue?

`PreparedStatement` is an object that represents a precompiled SQL statement,
that can be used to execute the statement multiple times efficiently.

`ResultSet` is the Java representation of the result set of a database query obtained from a `Statement` object.
A default `ResultSet` object is not updatable and has a cursor that moves forward only.

The parameters in `PreparedStatement` and `ResultSet` are indexed beginning at 1, not 0.
When an invalid index is passed to the `PreparedStatement` or `ResultSet` methods, an `IndexOutOfBoundsException` is thrown.
This can cause the program to crash or behave unexpectedly, leading to a poor user experience.

This rule raises an issue for the `get` methods in `PreparedStatement` and the `set` methods in `ResultSet`.

== How to fix it

Ensure the index passed to the `PreparedStatement` and `ResultSet` methods is valid.


=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
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

[source,java,diff-id=1,diff-type=compliant]
----
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);
  // ...
}
----

== Resources
=== Documentation

* https://docs.oracle.com/en/java/javase/20/docs/api/java.sql/java/sql/PreparedStatement.html[Oracle SDK 20 - PreparedStatement]

* https://docs.oracle.com/en/java/javase/20/docs/api/java.sql/java/sql/ResultSet.html[Oracle SDK 20 - ResultSet]

* https://docs.oracle.com/en/java/javase/20/docs/api/java.sql/java/sql/Connection.html#prepareStatement(java.lang.String)[Oracle SDK 20 - Connection#prepareStatement]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

* "[PreparedStatement|ResultSet]" indices start at 1.
* This "PreparedStatement" only has n parameters.


endif::env-github,rspecator-view[]
