通过属性配置文件编写JDBC程序

package com.bjpowernode.jdbc;

import java.sql.*;
import java.util.ResourceBundle;
/*
编程思想:
    将连接数据库时可变化的4条信息都写到配置文件中,以后需要连接其他数据库的时候,可直接修改配置文件,不用修改java程序。
    这4个信息分别是:driver、url、user、password。
 */

public class 通过属性配置文件编写JDBC程序 {
    public static void main(String[] args) {
        //资源绑定器(db.properties必须省略扩展名)
        ResourceBundle bundle = ResourceBundle.getBundle("resources\\db");
        //通过属性配置文件拿到信息
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //1.注册驱动
            Class.forName(driver);
            //2.获取连接(这里的url、user、password和上行代码的参数driver都来源于属性配置文件)
            conn = DriverManager.getConnection(url,user,password);
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            //4.执行sql语句
            String sql = "select a.ename as '员工',b.ename as '领导' from emp a left join emp b on a.mgr = b.empno";
            rs = stmt.executeQuery(sql);
            //5.处理查询结果集
            while(rs.next()){
                String ename = rs.getString("员工");
                String lname = rs.getString("领导"); //这里是根据查询结果的字段名获取对应值
                System.out.println(ename + "," + lname);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //6.释放资源(注意关闭顺序)
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

                        

                                         属性配置文件在IDEA中目录所处位置

                                                属性配置文件db.properties中的内容 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值