如何在 JDBC 中调用存储过程

2022-09-04 00:43:51

对于家庭作业,我必须创建一个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;

完成此操作后,我需要对所述过程进行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);

我在尝试捕获块中有上述内容,该块不断抛出错误。我已经根据我在其他网站上看到的内容尝试了字符串“in”的几个变体:in = “{调用ADDFACULTYDEPSAL ...in = “call ADDFACULTYDEPSAL ...

看这里:MySQL连接器指南我还尝试将stmt更改为可调用语句,如下所示:

CallableStatement stmt;
if(a == 1){
    stmt = dbConnection.prepareCall("{call ADDFACULTYDEPTSAL(?,?,?)}");
} else {
    stmt = dbConnection.prepareCall("{call ADDFACULTYUNISAL(?,?,?)}");
}

但是,尝试这种方式似乎不起作用,因为我需要将两个以上的变量传递到过程中。

谁能告诉我我做错了什么?


答案 1

你快到了:

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();
}

答案 2

推荐