您可以使用 CallableStatement 介面呼叫 SQL 預存程序。 Callable 語句可以有輸入參數、輸出參數或兩者。
您可以使用 prepareCall() 建立 CallableStatement(介面)的物件> Connection 介面的方法。此方法接受一個表示呼叫預存程序的查詢的字串變量,並傳回一個 CallableStatement 物件。
假設您有一個過程名稱myProcedure 在資料庫,您可以準備一個可呼叫語句:
//Preparing a CallableStatement CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
然後,您可以使用CallableStatement 介面的setter 方法為佔位符設定值,並使用execute() 方法執行可呼叫語句,如下所示。
cstmt.setString(1, "Raghav"); cstmt.setInt(2, 3000); cstmt.setString(3, "Hyderabad"); cstmt.execute();
如果該過程沒有輸入值,您只需準備可呼叫語句並執行它,如下所示:
CallableStatement cstmt = con.prepareCall("{call myProcedure()}"); cstmt.execute();
假設MySQL 資料庫中有一個名為Dispatches 的表,其中包含以下資料:
+--------------+------------------+------------------+----------------+ | 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 | +--------------+------------------+------------------+----------------+
如果我們建立了一個名為myProcedure 的程序來從此表中檢索值,如下所示:
Create procedure myProcedure () -> BEGIN -> SELECT * FROM Dispatches; -> END //
下面是使用JDBC 程式呼叫上述預存程序的JDBC 範例。
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 { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Preparing a CallableStateement CallableStatement cstmt = con.prepareCall("{call myProcedure()}"); //Retrieving the result 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
以上是如何在 JDBC 解釋中使用可調用語句呼叫預存程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!