如何在JDBC中调用存储过程

时间:2015-10-11 03:41:10

标签: java oracle stored-procedures jdbc plsql

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

我在try catch块中有上述内容,不断抛出错误。我已经在字符串""中尝试了几种变体。基于我在其他网站上看到的内容:     in =" {call ADDFACULTYDEPSAL ...     in ="调用ADDFACULTYDEPSAL ...

在这里查看:MySQL Connector Guide 我也尝试将stmt更改为可调用语句:

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

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

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

1 个答案:

答案 0 :(得分:14)

你快到了那里:

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