09_database_06_jdbc-5

第八十一章 CallableStatement接口的基本使用方法

1. 简介

CallableStatement接口继承自PreparedStatement接口,用于调用数据库中的存储过程(Stored Procedure)。存储过程的运行是在数据库内部进行的。存储过程除了能查询并返回数据之外,存储过程还支持IN、OUT参数。所以,这也使得CallableStatement接口的使用方法与PreparedStatement稍有不同。

2. 基本使用方法

CallableStatement对象是通过调用Connection对象的prepareCall()方法创建的。prepareCall()方法有三种形式,既支持创建使用默认类型的ResultSet的CallableStatement对象,也支持开发人员创建指定类型的ResultSet的CallableStatement对象。这与创建Statement对象过程相似。我们将在介绍事务处理时介绍ResultSet的另一种能力Holdability。

如下面的例子所示,变量callStoredProcedure表示的是示例即将调用存储过程countOfStudents来计算学生的人数。这个存储过程接收一个参数,其值可在后续代码中设置。然后,示例创建了一个CallableStatement对象。当查询数据时,它会返回一个默认类型的ResultSet对象。

String callStoredProcedure = "{call countOfStudents(?)}";
try (CallableStatement stmt = con.prepareCall(callStoredProcedure)) {
    stmt.setString(1, "Female");

    ResultSet result = stmt.executeQuery();
}

在创建出CallableStatement对象之后,我们可以通过使用set*()方法传递参数的值。这与PreparedStatement的使用方法十分相似。如果存储过程是用来查询数据的话,可以调用executeQuery()方法,通过使用返回的ResultSet对象来获取查询结果。如果存储过程是用来更新数据的话,可以调用executeUpdate()方法运行该存储过程。

String callStoredProcedure = "{call updateStudentName(?, ?)}";
try (CallableStatement stmt = con.prepareCall(callStoredProcedure)) {
    stmt.setInt(1, 0001);
    stmt.setString(2, "Amy");

    stmt.executeUpdate();
}

在返回数据的同时,存储过程还支持OUT参数,我们称之为输出参数。为了能够获取输出参数的值,CallableStatement新增了registerOutParameter()方法。在使用时,开发人员需要在运行存储过程之前,告知CallableStatement对象哪些参数是输出参数。在如下的例子中,我们将调用存储过程countOfStudents。它的第一个参数是学生的性别,第二个参数是一个输出参数,表示学生数量。存储过程countOfStudents的定义如下。

CREATE PROCEDURE countOfStudents (
    p_gender IN VARCHAR(10),
    p_countOfStudent OUT int)
AS
BEGIN
    select count(*) INTO p_countOfStudent FROM Student WHERE gender = p_gender;
END;

这里,我们需要指出的是,我们建议在处理完ResultSet对象之后再获取输出对象的值,以避免数据库不兼容问题。

String callStoredProcedure = "{call countOfStudents(?)}";
try (CallableStatement stmt = con.prepareCall(callStoredProcedure)) {
    stmt.setString(1, "Female");

    stmt.registerOutParameter(2, java.sql.Types.INTEGER);

    ResultSet result = stmt.executeQuery();
    while (result.next()) {
        ...
    }

    int theOutParameter = stmt.getInt(2);
    ...
}

3. 小结

本章介绍了CallableStatement的使用方法。CallableStatement专门用于调用存储过程。存储过程是运行在数据库中的"函数";它能够向Java应用程序返回查询结果,也可以修改数据库中的数据。

上一章
下一章

注册用户登陆后可留言

Copyright  2019 Little Waterdrop, LLC. All Rights Reserved.