Topic: [个人原创]通用的JDBC的try…catch…finally模板

  Print this page

1.[个人原创]通用的JDBC的try…catch…finally模板 Copy to clipboard
Posted by: jerryjerry123
Posted on: 2005-05-12 10:06

在日常的开发中, 我发现JDBC操作的Exception处理方法可总结为下面模板, 希望对大家有用.
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs=null;

try {
Class.forName("oracle.jdbc.driver.OracleDriver");

// Get connection from DriverManager or from DataSource
conn = DriverManager.getConnection("connection string", "username", "pwd");

stmt = conn.prepareStatement("SELECT count( * ) FROM user_objects order by object_name");
rs = stmt.executeQuery();
if (rs.next())
{
……
……
}
rs.close();

} catch (Exception e)
{
System.out.println("[Exception] - " + e.toString());
} finally {
try {
if (stmt != null)
stmt.close();

if (conn != null)
conn.close();
} catch (Exception fe)
{
System.out.println("[Exception] - " + fe.toString());
}
}

2.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: lqefn
Posted on: 2005-06-03 13:53

没有什么用处。

3.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: lqefn] Copy to clipboard
Posted by: YuLimin
Posted on: 2005-06-04 09:07

if (rs.next())
{
……
……
}

一般是
while(rs.next())
{
……
……
}

4.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: anit
Posted on: 2005-06-22 14:01

未免太简单了点嘛~

5.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: YuLimin] Copy to clipboard
Posted by: serena
Posted on: 2005-07-07 10:12

YuLimin wrote:
if (rs.next())
{
……
……
}

一般是
while(rs.next())
{
……
……
}


佩服,我都没有看的这样仔细

6.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: diystyle
Posted on: 2005-07-14 08:54

太老了吧

7.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: newbiemen
Posted on: 2005-07-20 10:25


query = "SELECT COUNTStart FROM cms_users";
    stmt.execute(query);
    rs = stmt.getResultSet();
    if (rs.next()) {
      int count = rs.getInt(1);
      System.out.println("count = " + count);
    }
    query = "SELECT USR_ID, USR_EMAIL, USR_GLOB_SUB FROM cms_users ORDER BY usr_id";
    rs = stmt.executeQuery(query);
//    rs = stmt.getResultSet();
    while (rs.next()) {
      double usrId = rs.getDouble(1);
      String usrEmail = new String(rs.getString(2));
      int usrGlobSub = rs.getInt(3);
      System.out.println("usrId = " + usrId + " usrEmail = " + usrEmail + " usrGlobSub = " + usrGlobSub);
    }
    rs.close();
    stmt.close();
    con.close();

8.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: wsfx
Posted on: 2005-09-08 11:47

早就用了,不过应该感谢楼主的热心!Blush

9.Re:[个人原创]通用的JDBC的try…catch…finally模板 [Re: jerryjerry123] Copy to clipboard
Posted by: wdmsyf
Posted on: 2005-11-19 08:27

这是有问题滴,当在执行rs.close之前 ,如果出现Excetion,那样会导致rs不能关闭而导致内存泄漏


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923