我们能否使用 Callable Statements 调用函数?请用 JDBC 中的示例进行说明。
与存储过程类似,您也可以在数据库中创建函数并存储它们。
语法
以下是创建 (MySQL) 数据库中函数的语法
CREATE FUNCTION Function_Name(input_arguments) RETURNS output_parameter BEGIN declare variables; statements . . . . . . . . . . return data_type; END
示例
假设我们在数据库中有一个名为 **Emp** 的表,其内容如下所示
+--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1970-01-08 | Hyderabad | | Sumith | 1970-01-08 | Vishakhapatnam | | Sudha | 1970-01-05 | Vijayawada | +--------+------------+----------------+
下面给出了创建函数的示例。在这里,我们创建了一个名为 **getDob()** 的函数,它接受员工的姓名作为参数,检索并返回 DOB 列的值。
CREATE FUNCTION getDob(emp_name VARCHAR(50)) RETURNS DATE BEGIN declare dateOfBirth DATE; select DOB into dateOfBirth from EMP where Name = emp_name; return dateOfBirth; END
使用 JDBC 调用函数
您可以像使用存储过程一样,使用 **CallableStatement** 对象调用函数。要使用 JDBC 程序调用函数,您需要:
连接到数据库。
创建一个 **PreparedStatement** 对象,并将其构造函数中传递以字符串格式表示的函数调用。
为占位符设置值。
执行 Callable 语句。
以下是从 JDBC 调用函数的查询
{? = call getDob(?)}如您所见,该查询包含与预处理语句和可调用语句相同的占位符 (?)。
在上面的查询中,第一个占位符表示函数的返回值,第二个占位符表示输入参数。
您需要使用 **registerOutParameter()** 方法(CallableStatement 接口的方法)将表示返回值的占位符注册为输出参数。为此方法,您需要传递一个表示占位符位置的整数值,以及一个表示参数的 SQL 类型(的整型变量)
cstmt.registerOutParameter(1, Types.DATE);
使用 setString() 方法为输入参数设置值。(因为 getDoc() 函数接受 VARCHAR 类型的值)。
示例
以下 JDBC 程序执行函数 **getDob** 并检索结果
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class CallingFunctionsUsingCallable2 {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql:///sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
cstmt.registerOutParameter(1, Types.DATE);
cstmt.setString(2, "Amit");
cstmt.execute();
System.out.print("Date of birth: "+cstmt.getDate(1));
}
}输出
Connection established...... Date of birth: 1970-01-08
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP