微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调用存储过程 笔记

操作就是把ResultSet打印到一个输出流。这是一个值得举例的很常用的例子,下面是调用一个存储过程的另外一个方法实现:

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,我建议整个采用存储过程的方式。


摘自:http://www.jb51.cc/article/p-ppktycqi-bko.html

原文地址:https://www.jb51.cc/postgresql/196413.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐