Getting the Return Value from JDBC MSSQL

后端 未结 2 759
挽巷
挽巷 2020-11-29 10:33

I\'m connecting to SQL Server (2005) through Java using the Microsoft SQL Server JDBC Driver 2.0.

How do I get the return value from a stored procedure? I\'m doing

相关标签:
2条回答
  • 2020-11-29 10:47
    c.prepareCall("? = ..");
    cs.execute();
    String returnedValue = cs.getString(1);
    

    (or the method of the appropriate type. You can use getObject alternatively)

    From an old getting started tutorial

    the getXXX methods in CallableStatement retrieve values from the OUT parameters and/or return value of a stored procedure.

    (Btw, the links that were provided by Umesh had this sort of information.)

    0 讨论(0)
  • 2020-11-29 10:59

    Bozho's 2nd revised answer was close but not quite there. It did lead me to the answer though.

    Taking the code example I started with we end up with:

    CallableStatement proc = connection.prepareCall("{ ? = call dbo.mySproc() }");
    proc.registerOutParameter(1, Types.INTEGER);
    proc.execute();
    int returnValue = proc.getInt(1);
    

    The key pieces here are the "? =" in front of the "call" in the prepareCall function which sets up a place for the return value and the registerOutputParameter. It has to be registered as an Integer, as the return value is always an int (at least in SQL Server, maybe it's different in other DBs). You therefore have to get it using getInt. I tested this method and it does work.

    0 讨论(0)
提交回复
热议问题