Call stored procedure in Java using CallableStatements

How can we call a stored procedure in Java using CallableStatements? Give an example.

Questions by khadarzone   answers by khadarzone

Showing Answers 1 - 6 of 6 Answers


first get connection object
Connection con=DriverManager.getConnection(); (we can get by datasourse object also)
CallableStatement cstmt=con.prepareCall("{ call procedurename(?,?,?,?) }");

cstmt.setString(1,ID);
cstmt.setString(2,name);
....
ucount=cstmt.executeUpdate();

  Was this answer useful?  Yes

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Sample
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }
        catch(ClassNotFoundException ex)
        {
            ex.printStackTrace();
        }
        Connection con=null;
        CallableStatement cstmt=null;
        try
        {
            con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
            "system","password");
            cstmt=con.prepareCall("{call p1}"); //called the procedure
                                        //how to create procedure had writen in  bellow
            cstmt.executeUpdate();
            System.out.println("done");
        }
        catch(SQLException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if(cstmt!=null) //close the callablestatement
                {
                    cstmt.close();
                    cstmt=null;
                }
            }
            catch(SQLException ex)
            {
                ex.printStackTrace();
            }
            try
            {
                if(cstmt!=null)  //close the connection
                {
                    cstmt.close();
                    cstmt=null;
                }
            }
            catch(SQLException ex)
            {
                ex.printStackTrace();
            }
        }
    }


//create the procedure,and execute in sql command prompy
CREATE PROCEDURE P1
AS
BEGIN
INSERT INTO PERSON VALUES(1,'SUBAS');
INSERT INTO PERSON VALUES(2,'VIJAY');
INSERT INTO PERSON VALUES(3,'CNU');
END;
}



  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions