Thursday, 25 July 2019

Java MySQL CallableStatement Example | Java MySQL Call Stored Procedure Example ( Callable Statement )


                      In this post, we will see Java MySQL CallableStatement Example OR Java MySQL Call Stored Procedure Example ( Callable Statement ).



                In previous posts, we have seen  
1. How to insert records (rows) into MySQL database: 
https://www.comrevo.com/2017/07/jdbc-code-to-insert-data-into-mysql-database.html

2. Java MySQL Insert Example using PreparedStatement:
https://www.comrevo.com/2019/07/java-mysql-insert-example-using-prepared-statement.html

               In this post, we will see how to use CallableStatement. It is used to run stored procedure from database.
               How to create procedures in MySQL database, check in following post:
https://www.comrevo.com/2019/07/how-to-create-procedure-in-mysql-database.html 


What is CallableStatement?
               CallableStatement is an Interface. PreparedStatement interface is extended in CallableStatement interface. 

               Check following example. We have already created procedure sample() which has three SQL queries (insert, update and select). You can add any number of queries in procedure. For details, check link https://www.comrevo.com/2019/07/how-to-create-procedure-in-mysql-database.html.

               Here sdldb is the database name. User name is sdl and password is sdl123.
        
Program (JdbcCS.java):
import java.sql.*;

class JdbcCS
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sdldb","sdl","sdl123");
CallableStatement st=con.prepareCall("call sample()");
ResultSet rs=st.executeQuery();
while(rs.next())
{
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");

System.out.println("\n");
}

rs.close();
st.close();
con.close();
}
               
Output:
parag@parag-Inspiron-N4010:~/Desktop/programs/jdbc$ javac JdbcCS.java
parag@parag-Inspiron-N4010:~/Desktop/programs/jdbc$ java JdbcCS
1221 SE PICT Pune

3221 TE VJTI Mumbai

1201 se vjti mumbai

3201 te coep Pune

4201 be wce Sangli

3303 TE GCOE Aurangabad


  
                       Hope, it will be helpful for you. Thank You.
                       Check jdbc code for fetching data from database in this post: http://www.comrevo.com/2017/07/jdbc-code-to-retrieve-data-from-mysql-database.html

No comments:

Post a comment