技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

我们可以使用可调用语句调用函数吗?请用 JDBC 中的示例进行说明?

jdbcjava 8mysqldatabasemysqli

与过程一样,您也可以在数据库中创建函数并存储它们。

语法

以下是在(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://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));
   }
}

输出

Connection established......
Date of birth: 1970-01-08


相关文章