我們能否使用 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

更新於: 2019-07-30

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.