我如何从sqlserver存储过程的return语句中获取一个值到java?

时间:2017-12-04 03:14:34

标签: java sql-server tsql stored-procedures return-value

我正试图进入一个名为valor的变量,在我的sql server存储过程中返回return语句... sqlserver存储过程工作正常,但问题是java ..

create procedure login
@cliente varchar(10),@pw varchar(10)
as begin
if exists(select cliente from seg where cliente=@cliente)
begin
if(select pw from seg where cliente=@cliente)=@pw
begin
   if(select privilegio from seg where cliente=@cliente)=0 begin
print 0
return 0
end
end

exec 'xd','xd'
  

这里我从PRINT行收到一条消息:   0

所以,我应该能够获取该值并使用此JAVA代码将其设置为变量valorReturn

String consulta="exec login '"+usr+"','"+pw+"'";
CallableStatement st=con.prepareCall(consulta);
st.setInt(1,10);
st.registerOutParameter(1, Types.INTEGER);
st.execute();
int valorReturn=st.getInt(1);

这是在控制台中打印的例外

  

com.microsoft.sqlserver.jdbc.SQLServerException:索引1超出范围。

谢谢,我感谢任何帮助! :)

1 个答案:

答案 0 :(得分:0)

SQL需要提供绑定到的输出参数。

SQL:

create procedure login
    @cliente varchar(10), @pw varchar(10), @result INT = -1 OUTPUT
    as begin
    if exists(select cliente from seg where cliente=@cliente)
    begin
    if(select pw from seg where cliente=@cliente)=@pw
        begin
        if(select privilegio from seg where cliente=@cliente)=0 begin
        print 0
        SET @result = 0 -- new parameter
       return 0
    end
end

爪哇:

    String consulta="exec login ?,?,?"; //moved out to parameters to avoid SQL injection.
    CallableStatement st= con.prepareCall(consulta);
    st.setString(1,usr);
    st.setString(2,pw);
    st.registerOutParameter(3, Types.INTEGER);
    st.execute();
    int valorReturn=st.getInt(3);

可在https://docs.microsoft.com/en-us/sql/connect/jdbc/using-a-stored-procedure-with-output-parameters

找到更多信息