JDBC学习之PreparedStatement的使用

PreparedStatement是Java中用于执行预编译SQL语句的接口,它继承自Statement接口。相比于Statement,PreparedStatement具有以下优点:
1. 防止SQL注入攻击:PreparedStatement使用占位符(?)来代替SQL语句中的参数,这样可以避免拼接字符串产生的SQL注入问题。
2. 提高性能:PreparedStatement可以预编译SQL语句,使得数据库能够缓存执行计划,从而提高执行效率。
3. 增加可读性:使用PreparedStatement可以将SQL语句与参数分离,使得代码更加清晰。
下面是使用PreparedStatement的步骤:
1. 创建PreparedStatement对象:使用Connection对象的prepareStatement()方法创建PreparedStatement对象。

PreparedStatement pstmt = connection.prepareStatement(sql);

2. 设置参数值:使用PreparedStatement对象的setXXX()方法设置SQL语句中的参数值,其中XXX为参数类型,如setString()、setInt()等。

pstmt.setString(1, "John");

3. 执行SQL语句:使用PreparedStatement对象的executeUpdate()方法执行SQL语句,返回受影响的行数。

int rows = pstmt.executeUpdate();

4. 关闭资源:关闭PreparedStatement对象和数据库连接。

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 {



            // 连接数据库



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

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



            



            // 创建PreparedStatement对象



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



            pstmt = connection.prepareStatement(sql);



            



            // 设置参数值



            pstmt.setString(1, "John");



            pstmt.setInt(2, 25);



            



            // 执行SQL语句



            int rows = pstmt.executeUpdate();



            System.out.println("受影响的行数:" + rows);



        } catch (SQLException e) {



            e.printStackTrace();



        } finally {



            // 关闭资源



            try {



                if (pstmt != null) {



                    pstmt.close();



                }



                if (connection != null) {



                    connection.close();



                }



            } catch (SQLException e) {



                e.printStackTrace();



            }



        }



    }

}

上述代码演示了如何使用PreparedStatement执行插入操作,使用了占位符(?)来替代SQL语句中的参数。在实际使用中,可以根据需要使用PreparedStatement执行查询、更新、删除等操作。

阅读剩余
THE END