溫馨提示×

JDBC學習之PreparedStatement的使用

小億
79
2024-01-10 17:42:07
欄目: 編程語言

PreparedStatement是Java中用于執(zhí)行預編譯SQL語句的接口,它繼承自Statement接口。相比于Statement,PreparedStatement具有以下優(yōu)點:
1. 防止SQL注入攻擊:PreparedStatement使用占位符(?)來代替SQL語句中的參數(shù),這樣可以避免拼接字符串產生的SQL注入問題。
2. 提高性能:PreparedStatement可以預編譯SQL語句,使得數(shù)據(jù)庫能夠緩存執(zhí)行計劃,從而提高執(zhí)行效率。
3. 增加可讀性:使用PreparedStatement可以將SQL語句與參數(shù)分離,使得代碼更加清晰。
下面是使用PreparedStatement的步驟:
1. 創(chuàng)建PreparedStatement對象:使用Connection對象的prepareStatement()方法創(chuàng)建PreparedStatement對象。

PreparedStatement pstmt = connection.prepareStatement(sql);

2. 設置參數(shù)值:使用PreparedStatement對象的setXXX()方法設置SQL語句中的參數(shù)值,其中XXX為參數(shù)類型,如setString()、setInt()等。

pstmt.setString(1, "John");

3. 執(zhí)行SQL語句:使用PreparedStatement對象的executeUpdate()方法執(zhí)行SQL語句,返回受影響的行數(shù)。

int rows = pstmt.executeUpdate();

4. 關閉資源:關閉PreparedStatement對象和數(shù)據(jù)庫連接。

pstmt.close();

connection.close();

完整示例代碼如下:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class PreparedStatementExample {

    public static void main(String[] args) {

        Connection connection = null;

        PreparedStatement pstmt = null;

        

        try {

            // 連接數(shù)據(jù)庫

            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/

            mydatabase", "root", "password");

            

            // 創(chuàng)建PreparedStatement對象

            String sql = "INSERT INTO users(name, age) VALUES(?, ?)";

            pstmt = connection.prepareStatement(sql);

            

            // 設置參數(shù)值

            pstmt.setString(1, "John");

            pstmt.setInt(2, 25);

            

            // 執(zhí)行SQL語句

            int rows = pstmt.executeUpdate();

            System.out.println("受影響的行數(shù):" + rows);

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            // 關閉資源

            try {

                if (pstmt != null) {

                    pstmt.close();

                }

                if (connection != null) {

                    connection.close();

                }

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

    }

}

上述代碼演示了如何使用PreparedStatement執(zhí)行插入操作,使用了占位符(?)來替代SQL語句中的參數(shù)。在實際使用中,可以根據(jù)需要使用PreparedStatement執(zhí)行查詢、更新、刪除等操作。

0