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

How to Safely Pass Parameters to a JDBC PreparedStatement?

Patricia Arquette
Release: 2024-11-25 00:31:10
Original
544 people have browsed it

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) {
            // ...
        }
    }

    // ...
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template