เหมือน Stored Procedures สามารถสร้าง Function ในฐานข้อมูลและเก็บไว้ได้
รูปแบบสร้าง Function (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 | +--------+------------+----------------+
สร้าง function 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
การเรียก Function ด้วย JDBC
ใช้ CallableStatement เหมือน stored procedures ขั้นตอน:
- เชื่อมต่อฐานข้อมูล
- สร้าง PreparedStatement ส่งคำสั่งเรียก function เป็น String
- ตั้งค่า placeholder
- รัน Callable statement
คำสั่งเรียก function:
{? = call getDob(?)}
Placeholder แรก = ค่าคืน, ตัวที่สอง = พารามิเตอร์เข้า ต้องลงทะเบียน placeholder แรกเป็น output parameter:
cstmt.registerOutParameter(1, Types.DATE);
ตั้งค่าพารามิเตอร์เข้า (VARCHAR):
cstmt.setString(2, "Amit");
ตัวอย่างโปรแกรม
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 {
// ลงทะเบียน Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// เชื่อมต่อ
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
// เตรียม 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