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

How to Safely Pass Parameters to a JDBC PreparedStatement in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 13:40:12623browse

How to Safely Pass Parameters to a JDBC PreparedStatement in Java?

Passing Parameters to a JDBC PreparedStatement

You're attempting to create a validation class for your Java program by connecting to a MySQL database and retrieving specific rows based on a constructor parameter. However, your code is not functioning as intended.

To resolve this issue, you need to modify your code to utilize the setString() method to set the userID parameter. This not only ensures that the statement is formatted correctly but also prevents SQL injection, which is important for database security.

Here's the updated code snippet:

import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;

public class Validation {

    private PreparedStatement statement;
    private Connection con;
    private String x, y;

    public Validation(String userID) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "");
            statement = con.prepareStatement(
                    "SELECT * from employee WHERE  userID = ?");
            statement.setString(1, userID);
            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                x = rs.getString(1);
                System.out.print(x);
                System.out.print(" ");
                y = rs.getString(2);
                System.out.println(y);
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

By incorporating these changes, you'll be able to effectively pass parameters to your JDBC PreparedStatement, mitigating SQL injection risks and ensuring the correct retrieval of data from your database.

The above is the detailed content of How to Safely Pass Parameters to a JDBC PreparedStatement in Java?. 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