/*
Przygotowanie bazy danych:
 
drop procedure sp_dodaj
create procedure sp_dodaj @x int output, @y int
as
begin
  set @x = @x+@y;
end;

declare @x int,  @y int
begin
  set @x=10;
  set @y=5;
  exec sp_dodaj @x output, @y
  select @x;
end;


drop function f_dodaj
create function f_dodaj(@x int, @y int) returns int
begin
  return @x+@y
end

select dbo.f_dodaj(3,4)
*/

import java.sql.*;

public class Wywolywanie
{
	public static void main(String[] args) throws ClassNotFoundException
	{
		Connection connection=null;
		CallableStatement cstmt=null;
		int wynik;
		try
		{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=KursBD;user=sa;password=sql2005");
			cstmt = connection.prepareCall( "{call sp_dodaj( ?, ? )}");
			cstmt.registerOutParameter( 1, Types.INTEGER );
			cstmt.setInt( 1, 100 );
			cstmt.setInt( 2, 20 );
			cstmt.execute();
			wynik = cstmt.getInt( 1 );
			System.out.println( wynik );
			cstmt.close();
			
			cstmt = connection.prepareCall( "{? = call f_dodaj( ?, ? )}");
			cstmt.registerOutParameter( 1, Types.INTEGER );
			cstmt.setInt( 2, 100 );
			cstmt.setInt( 3, 20 );
			cstmt.execute();
			wynik = cstmt.getInt( 1 );
			System.out.println( wynik );
			cstmt.close();
			
		}
		catch (SQLException sqle)
		{ 
			sqle.printStackTrace();
			while (sqle != null)
			{
				String logMessage = "\n SQL Error: "+
					sqle.getMessage() + "\n\t\t"+
					"Error code: "+sqle.getErrorCode() + "\n\t\t"+
					"SQLState: "+sqle.getSQLState()+"\n";
				System.out.println(logMessage);
				sqle = sqle.getNextException();
			}
		}
		finally
		{
			try { if ( connection != null ) connection.close(); }
			catch ( Exception e ) { e.printStackTrace(); }
		}
	}

}
