"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Safely Pass Parameters to a JDBC PreparedStatement?

How to Safely Pass Parameters to a JDBC PreparedStatement?

Published on 2025-02-05
Browse:686

How to Safely Pass Parameters to a JDBC PreparedStatement?

Passing Parameters to a JDBC PreparedStatement

Creating a validation class for a Java program often involves querying a database. The following code attempts to select a specific row from a table using a PreparedStatement with a parameter:

public class Validation {

    // ...

    public Validation(String userID) {
        try {
            // ...
            statement = con.prepareStatement(
                    "SELECT * from employee WHERE  userID = "   "''"   userID);
            // ...
        } catch (Exception ex) {
            // ...
        }
    }

    // ...
}

However, this code may not work because the SQL statement is not formatted correctly.

Solution:

To correctly pass a parameter to a PreparedStatement, use the setString() method:

statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);

This method sets the value of the first parameter (?) to the specified user ID. It ensures that the statement is formatted properly and prevents SQL injection, a security vulnerability that occurs when malicious SQL code is injected into a query.

For more information on using PreparedStatements, refer to the Java Tutorials.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3