== How to fix it in Java JDBC API

=== Code examples

include::../../common/fix/code-rationale.adoc[]

==== Noncompliant code example

[source,kotlin,diff-id=11,diff-type=noncompliant]
----
@RestController
public class ApiController(
    private val connection: Connection
) {
    @GetMapping(value = ["/authenticate"])
    @ResponseBody
    @Throws(SQLException::class)
    fun authenticate(
        @RequestParam("user") user: String?,
        @RequestParam("pass") pass: String?,
    ): ResponseEntity<String> {
        val query = "SELECT * FROM users WHERE user = $user AND pass = $pass"

        connection.prepareStatement(query).executeQuery(query).use { resultSet ->
            return if (resultSet == null || !resultSet.next()) {
                ResponseEntity("Unauthorized", HttpStatus.UNAUTHORIZED)
            } else {
                ResponseEntity("Authentication Success", HttpStatus.OK)
            }
        }
    }
}
----

==== Compliant solution

[source,kotlin,diff-id=11,diff-type=compliant]
----
@RestController
public class ApiController(
    private val connection: Connection
) {
    @GetMapping(value = ["/authenticate"])
    @ResponseBody
    @Throws(SQLException::class)
    fun authenticate(
        @RequestParam("user") user: String?,
        @RequestParam("pass") pass: String?,
    ): ResponseEntity<String> {
        val query = "SELECT * FROM users WHERE user = ? AND pass = ?"

        connection.prepareStatement(query).use {  statement ->
            statement.setString(1, user)
            statement.setString(2, pass)
            statement.executeQuery(query).use { resultSet ->
                return if (resultSet == null || !resultSet.next()) {
                    ResponseEntity("Unauthorized", HttpStatus.UNAUTHORIZED)
                } else {
                    ResponseEntity("Authentication Success", HttpStatus.OK)
                }
            }
        }
    }
}
----

=== How does this work?

include::../../common/fix/prepared-statements.adoc[]

