與過程一樣,您也可以在數(shù)據(jù)庫中創(chuàng)建函數(shù)并將其存儲。
語法
以下是在(MySQL)數(shù)據(jù)庫中創(chuàng)建函數(shù)的語法:
語法
以下是在(MySQL)數(shù)據(jù)庫中創(chuàng)建函數(shù)的語法: p>
CREATE FUNCTION Function_Name(input_arguments) RETURNS output_parameter BEGIN declare variables; statements . . . . . . . . . . return data_type; END
登錄后復(fù)制
示例
假設(shè)數(shù)據(jù)庫中有一個名為Emp的表,其內(nèi)容如下:
+--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1970-01-08 | Hyderabad | | Sumith | 1970-01-08 | Vishakhapatnam | | Sudha | 1970-01-05 | Vijayawada | +--------+------------+----------------+
登錄后復(fù)制
下面給出了創(chuàng)建函數(shù)的示例。在這里,我們創(chuàng)建一個名為 getDob() 的函數(shù),它接受員工的姓名,檢索并返回 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
登錄后復(fù)制
使用 JDBC 調(diào)用函數(shù)
您可以像存儲過程一樣使用 CallableStatement 對象調(diào)用函數(shù),以使用您需要的 JDBC 程序調(diào)用函數(shù)。
連接到數(shù)據(jù)庫。
創(chuàng)建一個 PreparedStatement 對象并向其構(gòu)造函數(shù)傳遞以字符串格式調(diào)用函數(shù)。
將值設(shè)置為占位符。
執(zhí)行 Callable 語句。
以下是從 JDBC 調(diào)用函數(shù)的查詢:
{? = call getDob(?)}
登錄后復(fù)制
正如您所觀察到的,查詢包含占位符 (?),就像準備好的語句和可調(diào)用語句一樣。
在上面的查詢中,第一個占位符表示函數(shù)的返回值,第二個占位符表示輸入
您需要使用 CallableStatement 接口的 registerOutParameter() 方法將表示返回值的占位符注冊為輸出參數(shù)。對于此方法,您需要傳遞一個表示占位符位置的整數(shù)值和一個表示(參數(shù)的)sql 類型的整數(shù)變量
cstmt.registerOutParameter(1, Types.DATE);
登錄后復(fù)制
使用 setString() 方法將值設(shè)置為輸入?yún)?shù)。 (因為 getDoc() 函數(shù)接受 VARCHAR 類型的值)。
示例
以下 JDBC 程序執(zhí)行函數(shù) getDob 并檢索結(jié)果:
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://localhost/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)); } }
登錄后復(fù)制
輸出
Connection established...... Date of birth: 1970-01-08
登錄后復(fù)制
以上就是我們可以使用 Callable 語句調(diào)用函數(shù)嗎?能用 JDBC 的例子解釋一下嗎?的詳細內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!