如何调用存储过程和准备语句 [英] How to call Stored Procedure and prepared statement

查看:647
本文介绍了如何调用存储过程和准备语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我想调用一个存储过程并执行一个Query。我在 statement.executeUpdate(); 中面临错误请帮助修复它。我不知道哪里错了。

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.

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

            }    

 }


推荐答案

如果要调用存储过程,请改用 CallableStatement (请参阅文档):

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

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

我也建议您检查此主题如何正确清理Java中的JDBC资源?这对我来说非常有帮助。

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

更新:根据此堆栈跟踪:

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语句。

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.

这篇关于如何调用存储过程和准备语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆