关闭数据库资源的新写法

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class SpringDataSourceTest {

    
/**
     * 
@param args
     
*/
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource
=(DataSource)ctx.getBean("dataSource");
        Connection con
=null;
        Statement stmt
=null;
        ResultSet res
=null;
        
try{
            con
=dataSource.getConnection();
            stmt
=con.createStatement();
            res
=stmt.executeQuery("select * from student");
            
while(res.next()){
                System.out.println(res.getInt(
"id"));
                System.out.println(res.getString(
"username"));
            }
        }
        
catch(SQLException e){
            e.printStackTrace();
        }
        
finally{
            
/*
            if(res!=null){
                try {
                    res.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
*/
            closeJdbcResource(res);
            closeJdbcResource(stmt);
            closeJdbcResource(con);
            
        }
    }
    
public static void closeJdbcResource(Object resource){
        Class clazz
=resource.getClass();
        
try {
            java.lang.reflect.Method method
=clazz.getMethod("close"null);
            method.invoke(resource, 
null);
        } 
catch (Exception e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
注释掉的是以前的写法。

posted on 2008-01-17 10:49 我为J狂 阅读(301) 评论(0)  编辑  收藏 所属分类: DataBase


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(11)

随笔分类(48)

文章分类(29)

常去逛逛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜