如何使用 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

更新於:2019年7月30日

6K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.