加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

调用存储过程 笔记

发布时间:2020-12-13 17:42:13 所属栏目:百科 来源:网络整理
导读:操作就是把ResultSet打印到一个输出流。这是一个值得举例的很常用的例子,下面是调用同一个存储过程的另外一个方法实现: public class ProcessPoetDeaths{ public abstract void sendDeath(String name,int age); } static void mapEarlyDeaths(ProcessPoet
操作就是把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.52php.cn/article/p-ppktycqi-bko.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读