如何在JDBC中使用可调用语句调用存储过程说明?
您可以使用CallableStatement接口调用SQL存储过程。Callable语句可以具有输入参数和/或输出参数。
您可以使用Connection接口的prepareCall()方法创建CallableStatement(接口)的对象。此方法接受表示查询的字符串变量来调用存储过程,并返回CallableStatement对象。
假设您在数据库中有一个过程名称myProcedure,则可以将可调用语句准备为:
//Preparing a CallableStatement CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
然后,您可以使用CallableStatement接口的setter方法为占位符设置值,并使用execute()
如下所示的方法执行callable语句。
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 { //注册驱动程序 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