Bạn có thể gọi stored procedure SQL bằng interface CallableStatement. CallableStatement có thể có tham số input, output, hoặc cả hai.
Tạo đối tượng CallableStatement (interface) bằng phương thức prepareCall() của interface Connection. Phương thức này chấp nhận biến String đại diện cho truy vấn gọi stored procedure và trả về đối tượng CallableStatement.
Giả sử có procedure tên myProcedure trong database, chuẩn bị CallableStatement như sau:
// Chuẩn bị CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
Thiết lập giá trị cho placeholder bằng setter methods của CallableStatement và thực thi bằng execute():
cstmt.setString(1, "Raghav"); cstmt.setInt(2, 3000); cstmt.setString(3, "Hyderabad"); cstmt.execute();
Nếu procedure không có tham số đầu vào, chỉ cần chuẩn bị và thực thi:
CallableStatement cstmt = con.prepareCall("{call myProcedure()}");
cstmt.execute();
Ví dụ
Giả sử bảng Dispatches trong MySQL có 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:
Create procedure myProcedure () -> BEGIN -> SELECT * FROM Dispatches; -> END //
Ví dụ
Chương trình JDBC gọi 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 {
// Đă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