如何从properties配置文件中对去jdbc链接配置

    我们在读取jdbc链接时,通常将链接信息写死在java文件中,或者从数据库链接池中读取。其实还有另外一种方法,将数据库链接信息写到properties文件中。这样做的好处是如果将来需要更换数据库,只需要修改properties文件,并且不需要重新编译即可执行。

    例如有一数据库配置文件db.properties。其中的内容如下:

    DBDriver=com.mysql.jdbc.Driver
    Connection=jdbc:mysql://127.0.0.1:3306/user

    User=root
    Password=root

 

    建立一个单例模式的类,用于获得数据库链接。

    public class DBConnection {
        private static DBConnection instance;
        public static synchronized Connection getConnection() throws Exception{
              if(instance==null){
              instance=new DBConnection();
        }
        return instance._getConnection();
        }

        private DBConnection() {

        }

       public Connection _getConnection() throws Exception {
           String sDBDriver=null;
           String sConnection=null;
           String sUser=null;
           String sPassword=null;
           Properties p=new Properties();

           //db.properties放在cn.com.showd.struts包中
           InputStream is=getClass().getResourceAsStream("/cn/com/showd/struts/db.properties");
           p.load(is);
           sDBDriver=p.getProperty("DBDriver");
           sConnection=p.getProperty("Connection");
           sUser=p.getProperty("User");
           sPassword=p.getProperty("Password");
           Properties pr=new Properties();
           pr.put("user", sUser);
           pr.put("password", sPassword);
           pr.put("characterEncoding", "UTF-8");
           pr.put("useUnicode","true");
          Class.forName(sDBDriver).newInstance();
  
           return DriverManager.getConnection(sConnection,pr);

 }


}

    这样我们就可以通过 _getConnection() 方法去得到一个connection了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值