从用户管理系统中复习javaweb知识3

上次复习了java连接jdbc,把数据库的连接信息放到程序里,但是感觉这样b格不是太高,我们换个数据库用户不能总是修改程序中的代码吧,把这些信息放置到配置文件中多好。java中常用的配置文件是properties文件。 properties文件内容格式是以键值对的形式存在key=value,可以用”#“号来注释一行内容。



这里关于properties就不再多介绍,让我们通过程序来看吧。

点击(此处)折叠或打开

  1. public class BaseDao {
  2.     // 获取配置信息
  3.     public String getProperties(String key) {
  4.         Properties pps = new Properties();
  5.         try {
  6.             BufferedInputStream in = new BufferedInputStream(
  7.                     new FileInputStream("src/db.properties"));
  8.             pps.load(in);
  9.             return pps.getProperty(key);

  10.         } catch (Exception e) {
  11.             // TODO Auto-generated catch block
  12.             e.printStackTrace();
  13.         }
  14.         return null;
  15.     }

  16.     /**
  17.      * 连接数据库
  18.      */
  19.     Connection conn = null;
  20.     BaseDao bd = null;

  21.     public Connection getConnection() {
  22.         try {
  23.             bd = new BaseDao();
  24.             Class.forName(bd.getProperties("drive"));

  25.             conn = DriverManager.getConnection(bd.getProperties("url"),
  26.                     bd.getProperties("uid"), bd.getProperties("pwd"));
  27.         } catch (Exception e) {
  28.             // TODO Auto-generated catch block
  29.             e.printStackTrace();
  30.         }
  31.         return conn;
  32.     }

  33.     /**
  34.      * 关闭数据库
  35.      */
  36.     public void closeConnection(Connection conn, PreparedStatement pstmt,
  37.             ResultSet rs) {

  38.         try {
  39.             if (rs != null) {
  40.                 rs.close();
  41.             }
  42.             if (pstmt != null) {
  43.                 pstmt.close();
  44.             }
  45.             if (conn != null && !conn.isClosed()) {
  46.                 conn.close();
  47.             }
  48.         } catch (SQLException e) {
  49.             // TODO Auto-generated catch block
  50.             e.printStackTrace();
  51.         }

  52.     }

  53. }
程序写完了,但是要有个前提,没有properties文件我们怎么用啊。在src下新建一个db.properties文件,过程也不用多说,直接上图。


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876573/viewspace-1815450/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29876573/viewspace-1815450/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值