java access data stored procedure

.
1 Using a stored procedure without parameters




When using a JDBC driver to call a stored procedure without parameters, you must use the call SQL escape sequence. The syntax for a call escape sequence with no parameters is as follows:

{call procedure-name}

As an instance, create the following stored procedure in the SQL Server 2005 AdventureWorks sample database:




SQL code :

CREATE PROCEDURE GetContactFormalNames

AS

BEGIN

   SELECT TOP 10 Title + ' ' + FirstName + ' ' + LastName AS FormalName

   FROM Person.Contact

END This stored procedure returns a single result set containing a column of data consisting of the salutation, first name, and last name of the first ten contacts in the Person.Contact table.




In the example below, this function is passed an open connection to the AdventureWorks sample database, and then the GetContactFormalNames stored procedure is called using the executeQuery method.




Java code:

Method 1: Statement stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}");




      while (rs.next()) {

         System.out.println(rs.getString("FormalName"));

      }

Method 2: CallableStatement callstat = con.prepareCall("{call dbo.GetContactFormalNames}"); ResultSet rs = callstat .executeQuery(); while(rs.next()){ System.out.println(rs.getString(2)); }

2 Using a stored procedure with input parameters When calling a stored procedure with parameters




using the JDBC driver, The call SQL escape sequence must be used in conjunction with the prepareCall method of the SQLServerConnection class. The syntax for a call escape sequence with an IN parameter is as follows:

{call procedure-name[([parameter][,[parameter]]...)]}




When constructing a call escape sequence, use ? (question mark) character to specify the IN parameter. This character acts as a placeholder for parameter values ​​to be passed to the stored procedure. A parameter can be assigned a value using one of the setter methods of the SQLServerPreparedStatement class. The setter methods available are determined by the data type of the IN parameter.

When passing a value to a setter method, you must specify not only the actual value to be used in the parameter, but also the ordinal position of the parameter in the stored procedure. For example, if the stored procedure contains a single IN parameter, its ordinal value is 1. If the stored procedure contains two parameters, the first ordinal value is 1 and the second ordinal value is 2.

As an example of how to call a stored procedure with an IN parameter, use the uspGetEmployeeManagers stored procedure in the SQL Server 2005 AdventureWorks sample database. This stored procedure accepts a single input parameter named EmployeeID, which is an integer value, and returns a recursive list of employees and their managers based on the specified EmployeeID. Here is the Java code that calls this stored procedure:




Java code :

                          

      PreparedStatement pstmt = con.prepareStatement("{call dbo.uspGetEmployeeManagers(?)}");

      pstmt.setInt(1, 50);

      ResultSet rs = pstmt.executeQuery() ;

      while (rs.next()) {

         System.out.println("EMPLOYEE:");

        System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName")) ;

         System.out.println("MANAGER:");

         System.out.println(rs.getString("ManagerLastName") + ", " + rs.getString("



      }

     




3 Using a stored procedure with output parameters When calling such a stored procedure

using the JDBC driver, you must use the call SQL escape sequence in conjunction with the prepareCall method of the SQLServerConnection class. The syntax for a call escape sequence with an OUT parameter is as follows:

{call procedure-name[([parameter][,[parameter]]...)]}




When constructing a call escape sequence, use ? (question mark) character to specify the OUT parameter. This character acts as a placeholder for the parameter value to be returned from this stored procedure. To specify values ​​for OUT parameters, you must specify the data type of each parameter using the registerOutParameter method of the SQLServerCallableStatement class before running the stored procedure.




The value specified for an OUT parameter using the registerOutParameter method must be one of the JDBC data types contained in java.sql.Types, which in turn is mapped to one of the native SQL Server data types. For more information about JDBC and SQL Server data types, see Understanding JDBC Driver Data Types.




When you pass a value to the registerOutParameter method for an OUT parameter, you must specify not only the data type to use for the parameter, but also the parameter's ordinal position or the parameter's name in the stored procedure. For example, if the stored procedure contains a single OUT parameter, its ordinal value is 1; if the stored procedure contains two parameters, the first ordinal value is 1 and the second is 2.

As an example, create the following stored procedure in the SQL Server 2005 AdventureWorks sample database: Based on the specified integer IN parameter (employeeID), the stored procedure also returns a single integer OUT parameter (managerID). Based on the EmployeeID contained in the HumanResources.Employee table, the value returned in the OUT parameter is ManagerID.







In the following example, this function is passed an open connection to the AdventureWorks sample database, and then the GetImmediateManager stored procedure is called using the execute method:




Java code:

        

      CallableStatement cstmt = con.prepareCall("{call dbo.GetImmediateManager(?, ?)}" );

      cstmt.setInt(1, 5);

      cstmt.registerOutParameter(2, java.sql.Types.INTEGER);

      cstmt.execute();

      System.out.println("MANAGER ID: " + cstmt.getInt(2) );




This example uses ordinal positions to identify parameters. Alternatively, the parameter can be identified by its name rather than its ordinal position. The following code example modifies the previous example to illustrate how named parameters can be used in a Java application. Note that these parameter names correspond to the parameter names in the stored procedure's definition:




SQL code :

CREATE PROCEDURE GetImmediateManager

   @employeeID INT,

   @managerID INT OUTPUT

AS

BEGIN

   SELECT @managerID = ManagerID

   FROM HumanResources.Employee

   WHERE EmployeeID = @employeeID

END Stored procedures may return update counts and multiple result sets. The Microsoft SQL Server 2005 JDBC Driver follows the JDBC 3.0 specification, which states that multiple result sets and update counts should be retrieved before retrieving OUT parameters. That is, the application should first retrieve all ResultSet objects and update counts, and then use the CallableStatement.getter method to retrieve the OUT parameters. Otherwise, ResultSet objects and update counts that have not been retrieved will be lost when the OUT parameters are retrieved.




4 Using a stored procedure with a return status When calling such a stored procedure




using the JDBC driver, you must use the call SQL escape sequence in conjunction with the prepareCall method of the SQLServerConnection class. The syntax for a call escape sequence that returns a status parameter is as follows:

{[?=]call procedure-name[([parameter][,[parameter]]...)]}




When constructing a call escape sequence, use the ? (question mark) character to specify the return status parameter. This character acts as a placeholder for the parameter value to be returned from this stored procedure. To specify a value for the return state parameter, you must specify the data type of the parameter using the registerOutParameter method of the SQLServerCallableStatement class before executing the stored procedure.




In addition, when passing the return state parameter value to the registerOutParameter method, it is necessary to specify not only the data type of the parameter to be used, but also the ordinal position of the parameter in the stored procedure. For the return status parameter, its ordinal position is always 1 because it is always the first parameter when calling the stored procedure. Although the SQLServerCallableStatement class supports the use of parameter names to indicate specific parameters, you can only use the parameter's ordinal position number for return state parameters.

As an example, create the following stored procedure in the SQL Server 2005 AdventureWorks sample database:




SQL code :

CREATE PROCEDURE CheckContactCity

   (@cityName CHAR(50))

AS

BEGIN

   IF ((SELECT COUNT(*)

   FROM Person.Address

   WHERE City = @cityName) > 1)

   RETURN 1

ELSE

   RETURN 0

END This stored procedure returns a status value of 1 or 0, depending on whether the city specified by the cityName parameter can be found in the Person.Address table.




5 Using a stored procedure with an update count After building a call to a stored procedure using the SQLServerCallableStatement class, the stored procedure can be called using either the execute or executeUpdate methods. The executeUpdate method will return an int value containing the number of rows affected by this stored procedure, but the execute method does not return this value. If you use the execute method and you want to get a count of rows affected, you can call the getUpdateCount method after running the stored procedure. As an example, create the following table and stored procedure in the SQL Server 2005 AdventureWorks sample database: SQL code : CREATE TABLE TestTable
















  























   (Col1 int IDENTITY,

    Col2 varchar(50),

    Col3 int);




CREATE PROCEDURE UpdateTestTable

   @Col2 varchar(50),

   @Col3 int

AS

BEGIN

   UPDATE TestTable

   SET Col2 = @Col2, Col3 = @Col3

END; In the example below, This function is passed an open connection to the AdventureWorks sample database, the UpdateTestTable stored procedure is called using the execute method, and the getUpdateCount method is used to return the count of rows affected by the stored procedure.




Java code :

      CallableStatement cstmt = con.prepareCall("{call dbo.UpdateTestTable(?, ?)}");

      cstmt.setString(1, "A");

      cstmt.setInt(2, 100);

      cstmt.execute() ;

      int count = cstmt.getUpdateCount();

      cstmt.close();




      System.out.println("ROWS AFFECTED: " + count);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327053947&siteId=291194637