Connect to database and call stored procedure

      Connection con = null;
        CallableStatement proc_stmt = null;
        ResultSet rs = null;
        
        try {
            
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            
            con = DriverManager.getConnection("jdbc:sqlserver://MYSERVER;databaseName=MYDATABASE", "USERID", "PASSWORD");
            
            proc_stmt = con.prepareCall("{ call generateID(?) }");
            
            proc_stmt.setString(1, "employee");
            rs = proc_stmt.executeQuery();
            
            if (rs.next()) {
                int employeeId = rs.getInt(1);
                System.out.println("Generated employeeId: " + employeeId);
            } else {
                System.out.println("Stored procedure couldn't generate new Id");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            
            try {
                
                rs.close();
                proc_stmt.close();
                con.close();
                
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            
        }
        


 

In the second example we do about just the same as above except that this time we don't provide an argument to the stored procedure and we don't receive any return value.


        Connection con = null;
        CallableStatement proc_stmt = null;
        
        try {
            
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection("jdbc:sqlserver://MYSERVER;databaseName=MYDATABASE", "USERID", "PASSWORD");
            proc_stmt = con.prepareCall("{ call someStoredProc() }");
            
            proc_stmt.executeQuery();
            
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            
            try {
                
                proc_stmt.close();
                con.close();
                
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            
        }
       

0 comments:

                                                                

Site Meter