- public class ProcessPoetDeaths{
- public abstract void sendDeath(String name,int age);
- }
- static void mapEarlyDeaths(ProcessPoetDeaths mapper){
- Connection con = null;
- CallableStatement toesUp = null;
- try {
- con = ConnectionPool.getConnection();
- con.setAutoCommit(false);
- CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");
- toesUp.registerOutParameter(1,Types.OTHER);
- toesUp.execute();
- ResultSet rs = (ResultSet) toesUp.getObject(1);
- while (rs.next()) {
- String name = rs.getString(1);
- int age = rs.getInt(2);
- mapper.sendDeath(name,age);
- }
- rs.close();
- } catch (sqlException e) { // We should protect these calls. toesUp.close();
- con.close();
- }
- }
下面是调用该存储过程的Java方法,将结果输出到PrintWriter:
- PrintWriter:
- static void sendEarlyDeaths(PrintWriter out){
- Connection con = null;
- CallableStatement toesUp = null;
- try {
- con = ConnectionPool.getConnection();
- // Postgresql needs a transaction to do this... con.
- setAutoCommit(false); // Setup the call.
- CallableStatement toesUp = connection.prepareCall("{ ? = call list_early_deaths () }");
- toesUp.registerOutParameter(1,Types.OTHER);
- toesUp.execute();
- ResultSet rs = (ResultSet) toesUp.getObject(1);
- while (rs.next()) {
- String name = rs.getString(1);
- int age = rs.getInt(2);
- out.println(name + " was " + age + " years old.");
- }
- rs.close();
- }
- catch (sqlException e) { // We should protect these calls. toesUp.close(); con.close();
- }
- }
存储过程可以帮助你在代码中分离逻辑,这基本上总是有益的。这个分离的好处有:
1 快速创建应用,使用和应用一起改变和改善的数据库模式。
2 数据库模式可以在以后改变而不影响Java对象,当我们完成应用后,可以重新设计更好的模式。
3 存储过程通过更好的sql嵌入使得复杂的sql更容易理解。
4 编写存储过程比在Java中编写嵌入的sql拥有更好的工具--大部分编辑器都提供语法高亮!
5 存储过程可以在任何sql命令行中测试,这使得调试更加容易。
并不是所有的数据库都支持存储过程,但是存在许多很棒的实现,包括免费/开源的和非免费的,所以移植并不是一个问题。Oracle、Postgresql和DB2都有类似的存储过程语言,并且有在线的社区很好地支持。
存储过程工具很多,有像TOAD或TORA这样的编辑器、调试器和IDE,提供了编写、维护PL/sql或pl/pgsql的强大的环境。
存储过程确实增加了你的代码的开销,但是它们和大多数的应用服务器相比,开销小得多。如果你的代码复杂到需要使用DBMS,我建议整个采用存储过程的方式。