码迷,mamicode.com
首页 > 数据库 > 详细

DButil

时间:2016-11-12 02:10:13      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:cep   etc   void   loader   init   new   rgs   set   初始化   

纲要:

Properties prop = new Properties();

BasicDataSource ds = new BasicDataSorce();

Connection conn = ds.getConnection();

 

==================

package util;

import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

/**  * 该类用来管理连接  * 数据库连接信息,保存在属性文件中  * 使用连接池获取连接  */ public class DBUtil {    private static BasicDataSource ds;    static{     try {    //加载属性文件数据    Properties prop = new Properties();    prop.load    (DBUtil.class.getClassLoader().    getResourceAsStream    ("db.properties"));    String driverclass = prop.getProperty("jdbc.driverclass");    String url = prop.getProperty("jdbc.url");    String user = prop.getProperty("jdbc.user");    String password = prop.getProperty("jdbc.password");    String strMaxActive    = prop.getProperty("dbcp.maxActive");    String strInitSize    = prop.getProperty("dbcp.initSize");    //实例化,并初始化连接池    ds = new BasicDataSource();    ds.setDriverClassName(driverclass);    ds.setUrl(url);    ds.setUsername(user);    ds.setPassword(password);       ds.setMaxActive    (Integer.parseInt(strMaxActive));       ds.setInitialSize    (Integer.parseInt(strInitSize));       }  catch (IOException e) {    e.printStackTrace();    throw new RuntimeException    ("读取属性文件错误",e);   }  }     //2、创建连接  public static  Connection getConnection()    throws SQLException{   return ds.getConnection();  }     //3、归还连接  public static void close(Connection conn){   if(conn!=null){    try {     conn.close();    } catch (SQLException e) {     e.printStackTrace();     throw new RuntimeException     ("归还连接错误!",e);    }   }  }     //测试  public static void main(String[] args)    throws SQLException {   Connection conn = getConnection();   System.out.println   (conn.getClass().getName());   close(conn);  }  }

 

DButil

标签:cep   etc   void   loader   init   new   rgs   set   初始化   

原文地址:http://www.cnblogs.com/21heshang/p/6055943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!