Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

Stored Procedures คืออะไร? วิธีเรียกใช้ด้วยโปรแกรม JDBC


Stored procedures คือโปรแกรมย่อย (sub routines) หรือชุดคำสั่ง SQL ที่เก็บไว้ใน SQL catalog แอปพลิเคชันที่เข้าถึงฐานข้อมูลเชิงสัมพันธ์ (Java, Python, PHP ฯลฯ) เรียกใช้ได้

Stored procedures มีพารามิเตอร์ IN และ OUT หรือทั้งคู่ อาจคืน result sets (ถ้าใช้ SELECT) และอาจคืนหลาย result-sets

ตัวอย่าง

ตาราง Dispatches ใน MySQL:

+--------------+------------------+------------------+------------------+
| Product_Name | Date_Of_Dispatch | Time_Of_Dispatch | Location         |
+--------------+------------------+------------------+------------------+
| KeyBoard     | 1970-01-19       | 08:51:36         | Hyderabad        |
| Earphones    | 1970-01-19       | 05:54:28         | Vishakhapatnam   |
| Mouse        | 1970-01-19       | 04:26:38         | Vijayawada       |
+--------------+------------------+------------------+------------------+

สร้าง procedure myProcedure ดึงข้อมูล:

Create procedure myProcedure ()
->
BEGIN
->
SELECT * from Dispatches;
->
END //

ตัวอย่าง JDBC เรียก Stored Procedure

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CallingProcedure {
    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 myProcedure()}");
        // ดึงผลลัพธ์
        ResultSet rs = cstmt.executeQuery();
        while(rs.next()) {
            System.out.println("Product Name: " + rs.getString("Product_Name"));
            System.out.println("Date Of Dispatch: " + rs.getDate("Date_Of_Dispatch"));
            System.out.println("Time Of Dispatch: " + rs.getTime("Time_Of_Dispatch"));
            System.out.println("Location: " + rs.getString("Location"));
            System.out.println();
        }
    }
}

ผลลัพธ์

Connection established......
Product Name: KeyBoard
Date of Dispatch: 1970-01-19
Time of Dispatch: 08:51:36
Location: Hyderabad
Product Name: Earphones
Date of Dispatch: 1970-01-19
Time of Dispatch: 05:54:28
Location: Vishakhapatnam
Product Name: Mouse
Date of Dispatch: 1970-01-19
Time of Dispatch: 04:26:38
Location: Vijayawada