Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access these procedures.
Stored procedures contain IN and OUT parameters, or both. They may return result sets in case you use SELECT statements, they can return multiple result-sets.
Example
Suppose we have a table named Dispatches in the MySQL database with the following data:
+--------------+------------------+------------------+------------------+ | 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 | +--------------+------------------+------------------+------------------+
And if we have created a procedure named myProcedure to retrieve values from this table as shown below:
Create procedure myProcedure () -> BEGIN -> SELECT * from Dispatches; -> END //
Example
Following is a JDBC example that calls the above mentioned stored procedure using JDBC program.
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("Date Of Dispatch: "+rs.getTime("Time_Of_Dispatch")); System.out.println("Location: "+rs.getString("Location")); System.out.println(); } } }
Output
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