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?
You can call an SQL stored procedure with the execute, open, or get statement; in each case, you use the #sql directive. A stored procedure is a set of instructions for a database, like a function in EGL.
The interface CallableStatement extends PreparedStatement . It is used to call stored procedures.
To call a stored procedure using a JDBC program you need to: Register the driver: class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter. Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With