Java 如何在JDBC中调用存储过程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33061280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a stored procedure in JDBC
提问by Eric
For homework I have to create a pl/sql stored procedure to add a facutly member to a database
对于作业,我必须创建一个 pl/sql 存储过程以将 facutly 成员添加到数据库
CREATE OR REPLACE PROCEDURE ADDFACULTYDEPTSAL
(facid IN NUMBER,
facname IN VARCHAR,
depID IN NUMBER)
AS
sal NUMBER;
BEGIN
CALCSALDEPT(depID, sal);
IF sal >= 50000
THEN
sal := sal*.9;
ELSE
IF sal >= 30000
THEN
sal := sal*.8;
END IF;
END IF;
INSERT INTO FACULTY(fid, fname, deptid, salary)
VALUES(facid, facname, depID, sal);
END ADDFACULTYDEPTSAL;
Having done that, I need to make a java call for said procedure, which I've tired to do with:
完成后,我需要对上述过程进行 java 调用,我已经厌倦了这样做:
Statement stmt = dbConnection.createStatement();
String in;
if(a == 1){
in = "ADDFACULTYDEPTSAL("
+ fid.getText() + "','"
+ fname.getText() + "','"
+ did.getText() + "')";
} else {
in = "ADDFACULTYUNISAL("
+ fid.getText() + "','"
+ fname.getText() + "','"
+ did.getText() + "')";
}
stmt.executeQuery(in);
I have the above in a try catch block that keeps throwing an error. I have tried several variants on the string "in" based on what I saw on other websites: in = "{call ADDFACULTYDEPSAL ... in = "call ADDFACULTYDEPSAL ...
我在不断抛出错误的 try catch 块中有上述内容。根据我在其他网站上看到的内容,我在字符串“in”上尝试了几种变体:in = "{call ADDFACULTYDEPSAL ... in = "call ADDFACULTYDEPSAL ...
looking here: MySQL Connector GuideI also tried changing stmt to a callable statement as such:
看这里:MySQL 连接器指南我也尝试将 stmt 更改为可调用语句,如下所示:
CallableStatement stmt;
if(a == 1){
stmt = dbConnection.prepareCall("{call ADDFACULTYDEPTSAL(?,?,?)}");
} else {
stmt = dbConnection.prepareCall("{call ADDFACULTYUNISAL(?,?,?)}");
}
However, trying this way doesn't seem to work because I need to pass more than two variables into the procedure.
但是,尝试这种方式似乎不起作用,因为我需要将两个以上的变量传递到过程中。
Can anyone tell me what I'm doing wrong?
谁能告诉我我做错了什么?
采纳答案by Andreas
You were almost there:
你快到了:
String call = (a == 1 ? "{call ADDFACULTYDEPTSAL(?,?,?)}"
: "{call ADDFACULTYUNISAL(?,?,?)}");
try (CallableStatement stmt = dbConnection.prepareCall(call)) {
stmt.setInt(1, Integer.parseInt(fid.getText()));
stmt.setString(2, fname.getText());
stmt.setInt(3, Integer.parseInt(did.getText()));
stmt.execute();
}