您可以使用可调用语句对象调用函数,就像存储过程一样,以使用您需要的 JDBC 程序调用函数。
-
连接到数据库。
-
创建一个准备语句对象,并将函数调用以字符串格式传递给其构造函数。
-
将值设置为占位符。
-
执行可调用语句。
以下是从 JDBC 调用函数的查询:
{? = call getDob(?)}
正如您所观察到的,查询包含占位符 (?),就像准备好的和可调用的语句一样。
在上面的查询中,第一个占位符表示函数的返回值,第二个占位符表示输入参数。
您需要使用可调用语句接口的寄存器OutParameter()方法将表示返回值的占位符注册为输出参数。对于此方法,您需要传递一个表示占位符位置的整数值,以及一个表示 SQL 类型(参数)的整数变量
例
假设我们有一个名为“员工详细信息”的表,其中包含以下内容:
+--------+------------+----------------+ | 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://localhost/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