📜  JDBC-语句,PreparedStatement和CallableStatement(1)

📅  最后修改于: 2023-12-03 14:43:05.624000             🧑  作者: Mango

JDBC的介绍

JDBC是Java Database Connectivity的缩写,它是Java平台上用于执行SQL语句和数据库操作的标准API。每个大型应用程序都需要与数据库交互,而JDBC作为Java的核心类库之一,为Java程序员提供了一个标准的接口来连接和查询数据库。

语句对象介绍

Java中有三种执行SQL语句的方式,分别是Statement,PreparedStatement和CallableStatement。

Statement

Statement是简单的SQL语句执行方式,它的工作机制是将SQL语句传递给数据库,并由数据库直接执行。例如,对于下面的代码:

Connection connection = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mydatabase",
    "username",
    "password");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM customers;");

在这个例子中,Statement将SQL语句"SELECT * FROM customers;"发送到数据库,并将结果集存储在ResultSet对象中。然而,这种方法存在一些问题,其中最明显的是它容易受到SQL注入攻击。

PreparedStatement

PreparedStatement是Statement的改进版本,它通过将SQL查询和参数分开,从而减少了SQL注入的风险。PreparedStatement允许使用占位符(?)来代表查询中的变量,然后使用set方法传递每个变量的值。

例如,下面的代码会创建一个PreparedStatement来查询指定ID的客户信息:

Connection connection = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mydatabase",
    "username",
    "password");
PreparedStatement preparedStatement = connection.prepareStatement(
    "SELECT * FROM customers WHERE customer_id = ?");
preparedStatement.setInt(1, 1234);
ResultSet resultSet = preparedStatement.executeQuery();

上面的代码将查询结果存储在ResultSet对象中。

CallableStatement

CallableStatement是一种特殊的PreparedStatement,它用于调用数据库存储过程或函数。它包含了所有的PreparedStatement功能,同时还可以使用registerOutParameter方法来处理输出参数。

例如,下面的代码会调用一个存储过程并输出结果:

Connection connection = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mydatabase",
    "username",
    "password");
CallableStatement callableStatement = connection.prepareCall(
    "{CALL my_procedure(?, ?, ?)}");
callableStatement.setInt(1, 1234);
callableStatement.setInt(2, 5678);
callableStatement.registerOutParameter(3, Types.INTEGER);
callableStatement.execute();
int result = callableStatement.getInt(3);

上面的代码将调用名为"my_procedure"的存储过程,并将参数1234和5678传递给它。registerOutParameter方法将第三个参数标记为输出参数,该参数将在存储过程完成后被设置为一个整数值。

总结

通过使用Statement、PreparedStatement和CallableStatement,Java程序员可以安全、高效地执行SQL语句和数据库操作。由于PreparedStatement和CallableStatement的安全和可扩展性,大多数情况下建议使用它们而不是Statement。无论使用何种方式,都应该始终通过绑定变量来防止SQL注入攻击。