Home > Database > Mysql Tutorial > body text

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

Linda Hamilton
Release: 2024-11-24 13:40:12
Original
547 people have browsed it

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

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!

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