7.3. Prepared Statements

Prepared statements are a technique for executing parameterized SQL queries that can improve performance and reduce the risk of SQL injection. Precompiled statements have the following main advantages:

  1. Avoid SQL injection attacks.
  2. Improves performance because prepared statements are compiled once and then executed multiple times.

In Java, java.sql.PreparedStatementprepared statements are implemented using interfaces. Following are a few examples showing how to use prepared statements for various database operations.

7.3.1. Insert data

The following example shows how to insert data using prepared statements:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class PreparedStatementInsertExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1, "User 7");
            preparedStatement.setInt(2, 30);
            preparedStatement.executeUpdate();

            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7.3.2. Query data

The following example shows how to query data using prepared statements:

import java.sql.*;

public class PreparedStatementSelectExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            String sql = "SELECT * FROM users WHERE age > ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 30);
            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name") + ", Age: " + resultSet.getInt("age"));
            }

            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7.3.3. Update data

The following example shows how to update data using prepared statements:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class PreparedStatementUpdateExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            String sql = "UPDATE users SET age = ? WHERE name = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 31);
            preparedStatement.setString(2, "User 7");
            preparedStatement.executeUpdate();

            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7.3.4. Delete data

The following example shows how to delete data using prepared statements:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class PreparedStatementDeleteExample {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "mypassword";
            Connection connection = DriverManager.getConnection(url, username, password);

            String sql = "DELETE FROMusers WHERE age > ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1, 60);
            preparedStatement.executeUpdate();

            preparedStatement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

With these examples, you should have a clearer understanding of how to use prepared statements. Prepared statements enable you to use parameters in queries, improving performance and reducing the risk of SQL injection. In actual projects, try to use precompiled statements to execute SQL queries. Recommended reading:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

Guess you like

Origin blog.csdn.net/u010671061/article/details/131003202