JDBC工具类,把数据库信息写到配置文件中,在配置文件中修改数据库信息不用重启服务器就能修改成功。

把JDBC工具类中的数据库名,用户名,密码等信息放到properties配置文件中,在配置文件中修改数据库信息不用重启服务器就能修改成功。因为配置文件不需要编译,每次运行类自动加载。

public class JDBCUtils {

    //驱动
    private static String driverName;
    //JDBC链接串
    private static String url;
    //数据库名字
    private static String userName;
    //数据库密码
    private static String password;

    //静态代码块,目的:让第一次使用到JDBCUtils时加载驱动,第二次以后不再加载
    static {
        try {
            //获取配置文件
            Properties ps = new Properties();
            ps.load(new FileReader("jdbc_config.properties"));
            driverName = ps.getProperty("driverName");
            url = ps.getProperty("url");
            userName = ps.getProperty("userName");
            password = ps.getProperty("password");
            //1.加载驱动
            Class.forName(driverName);
        } catch (Exception e) {
            throw new RuntimeException("驱动加载失败");
            //当驱动加载失败时,让程序直接停止运行
        }
    }

    //获取数据库连接
    public static Connection getConnection() throws Exception {

        //2.获取数据库的连接对象
        Connection connection = DriverManager.getConnection(url,userName,password);
        return connection;
    }

    //关闭所有资源
    public static void closeAll(Connection con, Statement st, ResultSet rs)  {
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       if(rs != null) {
           try {
               rs.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
}

配置文件内容:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值