Giống như stored procedure, bạn cũng có thể tạo function trong database và lưu trữ chúng.
Cú pháp
Cú pháp tạo function trong database (MySQL):
CREATE FUNCTION Function_Name(input_arguments) RETURNS output_parameter
BEGIN
declare variables;
statements ...
return data_type;
END
Ví dụ
Giả sử có bảng Emp trong database với nội dung:
+--------+------------+----------------+ | Name | DOB | Location | +--------+------------+----------------+ | Amit | 1970-01-08 | Hyderabad | | Sumith | 1970-01-08 | Vishakhapatnam | | Sudha | 1970-01-05 | Vijayawada | +--------+------------+----------------+
Ví dụ tạo function getDob() nhận tên nhân viên, truy xuất và trả về giá trị cột 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
Gọi function bằng JDBC
Bạn có thể gọi function bằng đối tượng CallableStatement giống như stored procedure. Các bước:
Kết nối database.
Tạo đối tượng PreparedStatement và truyền lời gọi function dạng String cho constructor.
Thiết lập giá trị cho placeholder.
Thực thi CallableStatement.
Câu truy vấn gọi function từ JDBC:
{? = call getDob(?)}
Placeholder đầu tiên đại diện cho giá trị trả về, placeholder thứ hai là tham số đầu vào.
Đăng ký placeholder đại diện cho giá trị trả về làm tham số OUT bằng phương thức registerOutParameter() (của interface CallableStatement). Truyền vị trí placeholder và kiểu SQL:
cstmt.registerOutParameter(1, Types.DATE);
Thiết lập giá trị cho tham số đầu vào bằng setString() (vì getDob() chấp nhận VARCHAR):
Ví dụ
Chương trình JDBC sau thực thi function getDob và lấy kết quả:
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 {
// Đăng ký Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// Lấy kết nối
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Kết nối thành công......");
// Chuẩn bị CallableStatement
CallableStatement cstmt = con.prepareCall("{? = call getDob(?)}");
cstmt.registerOutParameter(1, Types.DATE);
cstmt.setString(2, "Amit");
cstmt.execute();
System.out.print("Ngày sinh: " + cstmt.getDate(1));
}
}
Kết quả
Kết nối thành công...... Ngày sinh: 1970-01-08