调用存储过程时,我使用以下代码:
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 中一无所获
最佳答案
您可以创建一个通用包装器,类似于以下内容:
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
并声明变量,但至少您现在有一个通用包装器来处理所有调用。关于java - 在Java中调用存储过程的简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14275376/