59 lines
2.1 KiB
Plaintext

== 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,kotlin,diff-id=1,diff-type=noncompliant]
----
val ps: PreparedStatement = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?")
ps.setDate(0, date) // Noncompliant
ps.setDouble(3, salary) // Noncompliant
val rs: ResultSet = ps.executeQuery()
while (rs.next()) {
val fname: String = rs.getString(0) // Noncompliant
// ...
}
----
==== Compliant solution
[source,kotlin,diff-id=1,diff-type=compliant]
----
val ps: PreparedStatement = con.prepareStatement("SELECT fname, lname FROM employees where hireDate > ? and salary < ?")
ps.setDate(1, date)
ps.setDouble(2, salary)
val rs: ResultSet = ps.executeQuery()
while (rs.next()) {
val fname: String = 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]