Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

java - How to call a stored procedure in JDBC

For homework I have to create a pl/sql stored procedure to add a facutly member to a database

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:

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 ...

looking here: MySQL Connector Guide I also tried changing stmt to a callable statement as such:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...