db2 如何调用存储过程和预准备语句

gopyfrb3  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(267)

在下面的代码中,我想调用一个存储过程并执行一个查询。我在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");

            }    

 }
deikduxw

deikduxw1#

小跑题:如果要调用存储过程,则应改用CallableStatement(请参见documentation):

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

我也建议你检查这个主题How to properly clean up JDBC resources in Java?。它对我很有帮助。

更新:基于此堆栈跟踪:

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

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

yebdmbv4

yebdmbv42#

我用这种方法得到了它:

PreparedStatement myStmt = conn.prepareStatement(sqlQuery);
    myStmt.setInt(1, id); //position of parameter (1,2,3....) , value

     ResultSet rs = myStmt.executeQuery();

    while (rs.next()) {
        int jobId = rs.getInt("jobId"); ....... }

相关问题