Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Stored Procedure là gì? Cách gọi stored procedure bằng chương trình JDBC?


Stored procedure là các chương trình con, đoạn mã SQL được lưu trong catalog SQL. Tất cả ứng dụng truy cập cơ sở dữ liệu quan hệ (Java, Python, PHP, v.v.) đều có thể truy cập các procedure này.

Stored procedure chứa tham số IN và OUT, hoặc cả hai. Chúng có thể trả về result set nếu dùng câu lệnh SELECT, có thể trả về nhiều result set.

Ví dụ

Giả sử có bảng Dispatches trong MySQL với dữ liệu:

+--------------+------------------+------------------+------------------+ 
| 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       | 
+--------------+------------------+------------------+------------------+

Tạo procedure myProcedure để truy xuất dữ liệu từ bảng này:

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

Ví dụ

Chương trình JDBC sau gọi stored procedure trên:

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 { 
        // Đă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 myProcedure()}"); 
        // Lấy kết quả 
        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(); 
        } 
    } 
}

Kết quả

Kết nối thành công...... 
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