简体   繁体   English

如何将 JDBC4PreparedStatement 与需要 OUT 参数的 MySQL 存储过程一起使用?

[英]How to use JDBC4PreparedStatement with a MySQL stored procedure expecting an OUT parameter?

I am trying to call a stored procedure from Java using JDBC4PreparedStatement.我正在尝试使用 JDBC4PreparedStatement 从 Java 调用存储过程。 The stored procedure takes in two input parameters and one output.存储过程接受两个输入参数和一个输出。 I set the two input parameters by calling preparedStatement.setString(index, param)我通过调用preparedStatement.setString(index, param)设置两个输入参数

but I tried the same for the output and get this error: OUT or INOUT argument 3 for routine db.deleteItem is not a variable or NEW pseudo-variable in BEFORE trigger但我对输出尝试了相同的方法并得到此错误: OUT or INOUT argument 3 for routine db.deleteItem is not a variable or NEW pseudo-variable in BEFORE trigger

Is there a specific type I need to use?我需要使用特定类型吗? If so, how do I set it?如果是这样,我该如何设置? I couldn't find any good examples.我找不到任何好的例子。

Thanks谢谢

You should not use a prepared statement for that, but a callable statement instead.您不应该为此使用准备好的语句,而应使用可调用语句。 You can consider a callable statement a prepared statement with extra features to support stored procedures (including things like OUT parameters).您可以将可调用语句视为具有额外功能以支持存储过程(包括OUT参数之类的内容)的准备好的语句。

To register out parameters, you can use CallableStatement.registerOutParameter .要注册参数,您可以使用CallableStatement.registerOutParameter

When we mark parameters as OUT or INOUT , the expectation is that the SP should be able to work with these parameters and at the same time it should be a Variable instead of a value.当我们将参数标记为OUTINOUT ,期望 SP 应该能够使用这些参数,同时它应该是一个变量而不是一个值。 This variable then can be used at a later point in time.然后可以在稍后的时间点使用此变量。

A value for an OUT / INOUT parameter to the SP doesn't make much sense as the SP can't manipulate the value and hence the error. SP 的 OUT / INOUT 参数的值没有多大意义,因为 SP 无法操纵该值,从而导致错误。 We just can pass values for IN parameters alone.我们只能单独为 IN 参数传递值。

You can refer to this documentation here which states:您可以在此处参考文档,其中指出:

To get back a value from a procedure using an OUT or INOUT parameter, pass the parameter by means of a user variable, and then check the value of the variable after the procedure returns.要使用 OUT 或 INOUT 参数从过程中取回值,请通过用户变量传递参数,然后在过程返回后检查变量的值。 (If you are calling the procedure from within another stored procedure or function, you can also pass a routine parameter or local routine variable as an IN or INOUT parameter.) (如果您从另一个存储过程或函数中调用该过程,您还可以将例程参数或局部例程变量作为 IN 或 INOUT 参数传递。)

So, what you can do is something similar to the accepted answer here !所以,你可以做的是类似于这里接受的答案!

CALL alextest10 ('p99', 'Madeuppy', '999', 'w9', @a_message);
SELECT @a_message;

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM