如何使用 JDBC API 调用数据库中已存在的函数?
您可以使用 **CallableStatement** 对象调用函数,就像调用存储过程一样。要使用 JDBC 程序调用函数,您需要:
连接到数据库。
创建一个 **PreparedStatement** 对象,并将函数调用以字符串格式传递给它的构造函数。
为占位符设置值。
执行 Callable 语句。
以下是从 JDBC 调用函数的查询
{? = call getDob(?)}正如您所看到的,该查询包含占位符 (?),就像预处理语句和可调用语句一样。
在上面的查询中,第一个占位符表示函数的返回值,第二个占位符表示输入参数。
您需要使用 **registerOutParameter()** 方法(CallableStatement 接口的方法)将表示返回值的占位符注册为输出参数。对于此方法,您需要传递一个整数,表示占位符的位置,以及一个整数变量,表示参数的 SQL 类型。
示例
假设我们有一个名为 EmployeeDetails 的表,内容如下所示
+--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1989-09-26 | Hyderabad | | Sumith | 1989-09-01 | Vishakhapatnam | | Sudha | 1980-09-01 | Vijayawada | +--------+------------+----------------+
我们创建了一个名为 getDob() 的函数,如下所示:
mysql> DELIMITER // ; mysql> 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// Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ;
此函数接受员工姓名作为参数,检索并返回指定员工的出生日期。
以下 JDBC 程序建立与 MySQL 数据库的连接,并通过传递员工姓名作为参数来调用名为 getDob() 的函数,并从函数的返回值中检索出生日期值。
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class CallingFunctionsExample {
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:///mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStatement to call a function
CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
//Registering the out parameter of the function (return type)
cstmt.registerOutParameter(1, Types.DATE);
//Setting the input parameters of the function
cstmt.setString(2, "Amit");
//Executing the statement
cstmt.execute();
System.out.print("Date of birth: "+cstmt.getDate(1));
}
}输出
Connection established...... Date of birth: 1970-01-08
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP