Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a procedure with JDBC

This is my function :

public static void execute_delete_on_db(String pass, String login, String port,
        String host, String table_name, String file_path) throws Exception {

    Class.forName("oracle.jdbc.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//"
            + host + ":" + port + "/xe", login, pass);

    PreparedStatement statement = null;

    Statement stmt = null;
    String query = "delete from AA_ALL";
    stmt = conn.createStatement();
    stmt.executeQuery(query);
    sql_statement.close();
    conn.commit();
    conn.close();
}

At least this is the most important part of my function. Above code works fine. I tried to execute my procedure by calling this sql statement :

  EXECUTE delete_all_rows_from_table('all');

In Java it looked like this :

String query = "EXECUTE delete_all_rows_from_table('all')";

On the database it is working fine, but in Java this is giving me the error. Can you tell me what am I doing wrong?

like image 562
westman379 Avatar asked Feb 02 '17 08:02

westman379


People also ask

Which is used to execute stored procedure from JDBC program?

The CallableStatement of JDBC API is used to call a stored procedure.

How do you trigger a stored procedure in Java?

Calling a Stored Procedure ResultSet rs = cs. executeQuery(); To call a stored procedure, use execute(), executeQuery(), or executeUpdate() methods depending on how many ResultSet objects the procedure returns.

How can you execute stored procedure in database?

Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value.


2 Answers

You can call your procedure and not execute it like so :

String query = "{call delete_all_rows_from_table(?)}"; 
CallableStatement statement = connection.prepareCall(query);  
statement.setString(1, "all");  
statement.execute(); 

You can learn more here : JDBC CallableStatement – Stored Procedure OUT parameter example and JDBC Stored Procedure

like image 178
YCF_L Avatar answered Sep 19 '22 05:09

YCF_L


Notice if the procedure got some out parameters, you would have to register the parameters.

Here is an example, assuming we already import the modules (java.sql.CallableStatement and java.sql.Types) and the connection has been established.

CallableStatement callStmt = conn.prepareCall("{CALL <PROCEDURE_NAME>(?, ?, ?)}");
callStmt.setString(1, data);
callStmt.registerOutParameter(2, Types.VARCHAR);
callStmt.registerOutParameter(3, Types.VARCHAR);
callStmt.executeQuery();

String outParameter1 = callStmt.getString(2);
String outParamenter2 = callStmt.getString(3);
like image 38
Steven T Avatar answered Sep 19 '22 05:09

Steven T