简体   繁体   English

如何使用 JDBC 执行过程

[英]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 :我试图通过调用这个 sql 语句来执行我的程序:

  EXECUTE delete_all_rows_from_table('all');

In Java it looked like this :在 Java 中它看起来像这样:

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.在数据库上它工作正常,但在 Java 中这给了我错误。 Can you tell me what am I doing wrong?你能告诉我我做错了什么吗?

You can call your procedure and not execute it like so :你可以call你的过程而不是像这样执行它:

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您可以在此处了解更多信息: JDBC CallableStatement – 存储过程 OUT 参数示例JDBC 存储过程

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.下面是一个例子,假设我们已经导入了模块(java.sql.CallableStatement 和 java.sql.Types)并且已经建立了连接。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM