java dbcp连接oracle数据库

public class DBUtil {
    
    private static BasicDataSource bs;
    
    static{
        //读取配置文件db.properties
        Properties pt=new Properties();
        try {
            pt.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
            String driver= pt.getProperty("driver");
            String url=pt.getProperty("url");
            String user=pt.getProperty("user");
            String pwd=pt.getProperty("pwd");
            String initsize= pt.getProperty("initsize");
            String maxsize=pt.getProperty("maxsize");
            bs=new BasicDataSource();
            bs.setDriverClassName(driver);
            bs.setUrl(url);
            bs.setUsername(user);
            bs.setPassword(pwd);
            bs.setInitialSize(new Integer(initsize));
            bs.setMaxActive(new Integer(maxsize));
            
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("加载配置文件失败");     
        }
    }
    
    //连接数据库方法
    public static Connection getConnection() throws SQLException{
            return bs.getConnection();
    }
    
    //关闭数据库连接
    public static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭连接失败");
            }
        }
        
    }
    
    //测试    是否连接oracle数据库
    public static void main(String[] args) {
        try {
            Connection conn=DBUtil.getConnection();
            System.out.println(conn);
            
        } catch (SQLException e) {
            e.printStackTrace();
        }    
    }
    

}

posted @ 2017-08-20 23:10  lamdan  阅读(486)  评论(0编辑  收藏  举报