Java 如何调用存储过程和准备好的语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18531206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:49:00  来源:igfitidea点击:

How to call Stored Procedure and prepared statement

javasqlstored-proceduresjdbcdb2

提问by 123HIS

In the below code I want to call one stored procedures and execute one Query. I am facing error at statement.executeUpdate();Please help in fixing it. I am not sure where it going wrong.

在下面的代码中,我想调用一个存储过程并执行一个查询。我在statement.executeUpdate();请帮助修复它时遇到错误。我不确定哪里出错了。

public void Dbexe() {

    Connection connection;
    connection = DatabaseConnection.getCon();
     CallableStatement stmt;
    try {
        stmt = connection.prepareCall("{CALL optg.Ld_SOpp}");
        stmt.executeUpdate();
        stmt.close();
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

     System.out.println("Stored Procedure executed");

     //PreparedStatement statement = null;
    // ResultSet rs = null;

    try{


     PreparedStatement statement;
    try {
        statement = connection.prepareStatement("MERGE INTO OPTG.R_VAL AS TARGET USING" + 
              ........... +
             "");

         statement.executeUpdate(); //Here the exception is thrown  
         statement.close();

         connection.commit();
         connection.close();


    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   

    // statement = connection.prepareStatement(query);

     //statement.close();

    }

    finally{

        System.out.println("Data is copied to the  Table");

            }    

 }

回答by dic19

Little off-topic: You should use CallableStatementinstead if you want to call a store procedure (see documentation):

小题外话:CallableStatement如果你想调用一个存储过程,你应该使用它(参见文档):

CallableStatement callableStatement = connection.prepareCall("{call opptymgmt.Load_SiebelOpportunity}");
ResultSet rs = callableStatement.executeQuery();

I would also suggest you check this topic How to properly clean up JDBC resources in Java?. It was very helpful to me.

我还建议您查看此主题如何正确清理 Java 中的 JDBC 资源?. 这对我很有帮助。

Update: based on this stack trace:

更新:基于此堆栈跟踪:

com.ibm.db2.jcc.am.mo: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=MERGE INTO OPPTYMGMT.REVENUE_VALIDAT;BEGIN-OF-STATEMENT;<variable_set>, DRIVER=4.7.85 

The problem seems to be in the sql sentence you're trying to execute. I mean, is an error from DB2, not java. You should check your sql statement.

问题似乎出在您尝试执行的 sql 语句中。我的意思是,是 DB2 的错误,而不是 java。你应该检查你的sql语句。