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

วิธีเรียก Stored Procedure ด้วย CallableStatement ใน JDBC


เรียก SQL stored procedures ด้วยอินเทอร์เฟซ CallableStatement ซึ่งรองรับ input parameters, output parameters หรือทั้งคู่

สร้าง CallableStatement object ด้วยเมธอด prepareCall() ของ Connection interface รับสตริงคำสั่งเรียก procedure คืน CallableStatement object

สมมติมี procedure ชื่อ myProcedure:

// Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");

ตั้งค่า placeholder ด้วย setter methods แล้วรันด้วย execute():

cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
cstmt.execute();

ถ้าไม่มี input parameters:

CallableStatement cstmt = con.prepareCall("{call myProcedure()}");
cstmt.execute();

ตัวอย่าง

ตาราง Dispatches และ procedure myProcedure เหมือนบทความก่อนหน้า

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