什么是存储过程?如何使用 JDBC 程序调用存储过程?
存储过程是子例程,是存储在 SQL 目录中的 SQL 语句片段。所有可以访问关系型数据库(例如,Java、Python、PHP 等)的应用程序都可以访问这些过程。
存储过程包含输入和输出参数,或者同时包含这两个参数。它们可以返回结果集(如果您使用的是 SELECT 语句),也可以返回多个结果集。
示例
假设我们有一个名为Dispatches的 MySQL 数据库表,其中包含以下数据
+--------------+------------------+------------------+------------------+ | 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://127.0.0.1/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("Date 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
广告