Dưới đây là ưu điểm của stored procedures:
Vì stored procedure được biên dịch và lưu trữ, khi gọi procedure thì phản hồi nhanh.
Có thể gom tất cả câu lệnh SQL cần thiết trong một procedure và thực thi cùng lúc.
Vì procedure lưu trên database server (nhanh hơn client). Có thể thực thi các truy vấn phức tạp nhanh hơn.
Sử dụng procedure tránh lặp code, thêm có thể dùng chức năng SQL nâng cao như gọi stored function.
Sau khi biên dịch stored procedure, có thể dùng trong bao nhiêu ứng dụng cũng được. Nếu cần thay đổi chỉ sửa procedure mà không động đến code ứng dụng.
Có thể gọi PL/SQL stored procedure từ Java và Java Stored procedure từ PL/SQL.
Ví dụ
Giả sử đã tạo bảng Employees với mô tả:
+----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Salary | int(11) | NO | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+
Giả sử procedure myProcedure chèn dữ liệu vào Employees:
Create procedure myProcedure (IN name VARCHAR(30), IN sal INT, IN loc VARCHAR(45)) -> BEGIN -> INSERT INTO Employees(Name, Salary, Location) VALUES (name, sal, loc); -> END //
Chương trình JDBC gọi stored procedure Java:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Example {
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/testdb";
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(?, ?, ?)}");
cstmt.setString(1, "Amit");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
cstmt.execute();
cstmt.setString(1, "Kalyan");
cstmt.setInt(2, 4000);
cstmt.setString(3, "Vishakhapatnam");
cstmt.execute();
}
}
Kết quả
Kết nối thành công......
Kiểm tra bảng Employees, thấy các hàng mới:
+-----------+--------+----------------+ | Name | Salary | Location | +-----------+--------+----------------+ | Amit | 3000 | Hyderabad | | Kalyan | 4000 | Vishakhapatnam | +-----------+--------+----------------+