Home >Database >Mysql Tutorial >How to Safely Pass Parameters to a JDBC PreparedStatement?

How to Safely Pass Parameters to a JDBC PreparedStatement?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 00:31:10600browse

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.

The above is the detailed content of How to Safely Pass Parameters to a JDBC PreparedStatement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn