Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calling Stored Procedure from Java Code

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 198
    Comment on it

    Let say you have requirement to call stored procedure from your Java code. You can use following sample code for your reference. Change the connection source as per your requirement and call the method.

    package com.app.util;
    
    import java.sql.*;
    
    public class StoredProcedureExample {
         public Connection conn = null;
    
         public void createDatabaseConnection() throws SQLException{
             String URL = "jdbc:oracle:thin:@mydatabase:1521:Oracle";
             String USER = "myuser";
             String PASS = "mypassword";
             conn = DriverManager.getConnection(URL, USER, PASS);
         }
    
         /**
          * Assuming you need to call procedure myStoreProcedure
          * It take integer as input
          * It return 3 paramter integer, varchar, and float
          * */
         public String callStoreProcedure() throws SQLException{
             try{
                     int myId = 10;
                     CallableStatement pstmt = conn.prepareCall("{call myStoreProcedure(?,?,?,?)}");
                     pstmt.setInt(1, myId);
                     pstmt.registerOutParameter(2, Types.INTEGER);
                     pstmt.registerOutParameter(3, Types.VARCHAR);
                     pstmt.registerOutParameter(4, Types.FLOAT);
                     pstmt.executeUpdate();
    
                     int myNo = pstmt.getInt(2);
                     String myName = pstmt.getString(3);
                     float mySalary = pstmt.getFloat(4);
                     System.out.print("My Details are" +myNo+" "+myName+" "+mySalary);
                     pstmt.close();
                     conn.close();
                     return myNo+" "+myName+" "+mySalary;
              }catch (SQLException e) {
                     System.err.println(e.getErrorCode() + e.getMessage()); 
                     conn.close();
                     return null;
                 }       
         }
    
         public static void main(String[] args){
           try{
             StoredProcedureExample spEx=new StoredProcedureExample();  
             spEx.createDatabaseConnection();
             spEx.callStoreProcedure();
           }catch(Exception e){
               e.printStackTrace();
           }
         }
    }    
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: