[Java Advanced] Detailed explanation of JDBC PreparedStatement

Insert image description here

In Java, interacting with relational databases is one of the most common tasks. JDBC (Java Database Connectivity) is a standard API of the Java platform, used to connect and operate various relational databases. Among them, PreparedStatementit is an important interface in JDBC, used to execute precompiled SQL statements. This blog will introduce JDBC in detail PreparedStatement, including its basic concepts, usage and best practices.

What is PreparedStatement?

PreparedStatementIt is an interface in JDBC used to execute precompiled SQL statements. Unlike ordinary SQL statements Statement, PreparedStatementSQL statements have been compiled before execution, so they are more efficient and secure, and can prevent SQL injection attacks. PreparedStatementIt is usually used to execute multiple similar SQL queries or updates. It only needs to be compiled once and executed multiple times.

CreatePreparedStatement

To create an PreparedStatementobject, you first need to obtain an Connectionobject, and then use prepareStatementthe method to pass in the SQL statement. Here is an example:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class PreparedStatementDemo {
    
    
    public static void main(String[] args) {
    
    
        // 获取数据库连接
        Connection connection = getConnection();

        try {
    
    
            // SQL 查询语句,使用 ? 作为占位符
            String sql = "SELECT * FROM users WHERE username = ?";

            // 创建 PreparedStatement 对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
    
    // 获取数据库连接的示例方法
    private static Connection getConnection() {
    
    
        // 实现获取数据库连接的逻辑,这里省略具体代码
        return null;
    }
}

In the above example, we created an object, which was used as placeholders PreparedStatementin the SQL query statement . You can later use the method to set specific values ​​for these placeholders.?setXXX

Setting parameters

PreparedStatementAllows us to set parameter values ​​for placeholders in SQL statements. There are many setXXXmethods for parameter setting of different data types, such as setInt, setString, setDoubleetc. Here is an example of setting parameters:

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

    // 设置第一个参数为字符串类型
    preparedStatement.setString(1, "Alice");

    // 设置第二个参数为整数类型
    preparedStatement.setInt(2, 30);

    // 执行 SQL 语句
    preparedStatement.executeUpdate();
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

In the above example, we used setStringthe and setIntmethods to set specific parameter values ​​for the two placeholders in the SQL statement.

Execute query

To perform query operations, you can use executeQuerythe method, which returns an ResultSetobject to store the query results. Here is an example:

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

    // 设置参数
    preparedStatement.setInt(1, 25);

    // 执行查询
    ResultSet resultSet = preparedStatement.executeQuery();

    // 处理查询结果
    while (resultSet.next()) {
    
    
        String username = resultSet.getString("username");
        int age = resultSet.getInt("age");
        System.out.println("Username: " + username + ", Age: " + age);
    }
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

In the above example, we executed a query operation with a placeholder, setIntset the parameter value of the placeholder through the method, then used executeQuerythe method to execute the query, and finally traversed ResultSetto obtain the query results.

perform update

To perform update operations (such as insert, update, delete), you can use executeUpdatethe method. Here is an example:

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

    // 设置参数
    preparedStatement.setInt(1, 28);
    preparedStatement.setString(2, "Alice");

    // 执行更新
    int rowCount = preparedStatement.executeUpdate();

    // 输出更新的行数
    System.out.println("Updated " + rowCount + " rows.");
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

In the above example, we perform an update operation with a placeholder, set the parameter value of the placeholder through the setIntand methods, and then use the method to perform the update operation and output the number of updated rows.setStringexecuteUpdate

Execute batch processing

PreparedStatementBatch processing is also supported, which means executing multiple SQL statements at once. This is useful for situations where similar SQL statements need to be executed frequently and can improve performance. Here is an example of batch processing:

try {
    
    
    String insertSql = "INSERT INTO users (username, age) VALUES (?, ?)";
    String updateSql = "UPDATE users SET age = ? WHERE username = ?";

    // 创建 PreparedStatement 对象
    PreparedStatement insertStatement = connection.prepareStatement(insertSql);
    PreparedStatement updateStatement = connection.prepareStatement(updateSql);

    // 设置参数并添加到批处理中
    for (int i = 1; i <= 3; i++) {
    
    
        insertStatement.setString(1, "User" + i);
        insertStatement.setInt(2, 25 + i);
        insertStatement.addBatch();

        updateStatement.setInt(1, 30 + i);
        updateStatement.setString(2, "User" + i);
        updateStatement.addBatch();
    }

    // 执行批处理
    int[] insertResult = insertStatement.executeBatch();
    int[] updateResult = updateStatement.executeBatch();

    // 输出批处理结果
    System.out.println("Inserted rows: " + Arrays.toString(insertResult));
    System.out.println("Updated rows: " + Arrays.toString(updateResult));
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

In the above example, we created two PreparedStatementobjects and used addBatchthe method to add multiple SQL statements to the batch, and then used executeBatchthe method to execute all the SQL statements in the batch at once.

Close PreparedStatement

After use PreparedStatement, it should be closed promptly to release resources. closeIt can be closed using the method PreparedStatement. Here is an PreparedStatementexample of closing:

try {
    
    
    // 创建 PreparedStatement 对象
    PreparedStatement preparedStatement = connection.prepareStatement(sql);

    // 设置参数...
    
    // 执行操作...
    
    // 关闭 PreparedStatement
    preparedStatement.close();
} catch (SQLException e) {
    
    
    e.printStackTrace();
}

Summarize

PreparedStatementIt is an important interface in JDBC for executing precompiled SQL statements. It has the advantages of efficiency, security and maintainability. In practical applications, using PreparedStatementcan effectively prevent SQL injection attacks and improve the performance of database operations. Through the introduction of this article, you should PreparedStatementhave a clearer understanding of the basic concepts and usage of . When writing database-related Java applications, consider using PreparedStatementto perform SQL operations.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133531760