3

调用存储过程时,我使用以下代码:

    connection = getConnection();
    stmt = connection.prepareCall("{call MPLOGIN (?, ?, ?, ?, ?, ?)}");
    stmt.setString("VUSCD", uscd);
    stmt.setString("VPWD", pwd);
    stmt.setString("VPCSQ", pcsq);
    stmt.setString("VHWID", hwid);
    stmt.registerOutParameter("VLOGID", OracleTypes.VARCHAR);
    stmt.registerOutParameter("VKQ", OracleTypes.VARCHAR);
    stmt.execute();
    String vlogid = stmt.getString("VLOGID");
    String vkq = stmt.getString("VKQ");

为少数程序编写这个无聊的包装器是没有问题的,但是如果有数百个程序,那真是一场噩梦。有没有比这种方式更简单的方法来调用存储程序?编辑:我认为使用 DB 中的过程参数的代码生成器是一种优雅的方式,但我在 java 中一无所获

4

4 回答 4

2

您可以,也许创建一个通用包装器,类似于以下内容:

public Map<String, String> SPWrapper(String call, Map<String, String> inParams, Map<String, OracleTypes> outParams)
{
    connection = getConnection();
    try 
    {
        stmt = connection.prepareCall(call);
        for(String inParam : inParams.keys())
        {
            stmt.setString(inParam, inParams.get(inParam));
        }
        for(String outParam : outParams.keys())
        {
            stmt.registerOutParameter(outParam, outParams.get(outParam));
        }

        stmt.execute();

        Map<String,String> results = new HashMap<String, String>();
        for(String outParam : outParams.keys())
        {
            results.put(outParam, stmt.getString(outParam));
        }

        return results;
    }
    catch (Exception e)
    {
        //LOG Exception
        return new HashMap<String, String>();
    }
    finally
    {
        connection.close();   //Do not leave connections open.
    }
}

您仍然需要传入call并声明变量,但至少您现在有一个通用包装器来处理您的所有调用。

于 2013-01-11T09:51:58.393 回答
2

我喜欢使用MyBatis数据映射器框架来解决此类问题。可以在http://loianegroner.com/2011/03/ibatis-mybatis-working-with-stored-procedures/找到使用 MyBatis 和存储过程的广泛示例

于 2013-01-11T10:44:02.257 回答
1

没有其他办法。是的,这很无聊,但程序的数量是有限的。此过程类似于 Java 中的方法,因此您应该按照规定的规则对其进行操作。您只能做一件方便的事情 - 创建特殊的类,它将包含每个过程的包装方法。在这种情况下,在业务代码中调用它们会更优雅,如下所示:

String[] result = DAO.MPLOGIN(uscd, pwd, pcsq, hwid);

但是在此方法中,您必须复制上面提到的代码。

于 2013-01-11T09:51:06.480 回答
0

在数据库客户端中,诸如 myproc(10,20) 之类的存储过程仅通过语句 select myproc(10,20); 调用;

所以在你的 JDBC 程序中你可以这样做:connection = getConnection(); stmt = connection.createStatement(); stmt.executeQuery("选择 myproc(10,20)");

如果过程正在返回某些东西,则将其放入 ResultSet

于 2013-01-11T10:30:40.937 回答