一招,java和数据库的配置文件轻松配置

在java中要实现和MySql的更方便的连接以及保证安全,那么配置文件必不可少。下面我就献上,我认为一招鲜吃遍天搞定配置文件的方法。

首先要知道,很多公司为了保证数据库的安全性,对于账户明和密码都是定时更新的,如果在JDBC中将用户名和密码定死,那么后期修改起来就变得异常的麻烦。为了解决这个问题,引出了配置文件的存在。

首先在src下建立一个名字为user,后缀为properties的文件。紧接着把帐户名、密码、JDBC协议放进去。

db.username=root
db.password=123456
db.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
db.driverClassName=com.mysql.jdbc.Driver
/*
?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
这一串是url的几个参数。第一个是设置时区的;后面的是设置字符集格式,防止出现插入中文字段出现乱码的。
*/

 

public class JdbcUtil {
    private static Properties properties = new Properties();
    static
    {
        //写一个类需要动态的获取某个文件的位置,从而能够获取此文件的资源
        InputStream res = JdbcUtil.class.getResourceAsStream("/user.properties");
        try {
            //加载信息到集合中
            properties.load(res);
        } catch (IOException e) {
            //转换成运行时异常,可以抛出
            throw new RuntimeException(e);
        } finally {
            if(res!=null){
                try {
                    res.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //以下个人认为可写可不写
        properties.getProperty("db.username");
        properties.getProperty("db.password");
        properties.getProperty("db.url");
        properties.getProperty("db.driverClassName");
    }
    //连接
    public static Connection getConnection() throws SQLException {

        Connection connection = DriverManager.getConnection(properties.getProperty("db.url"), properties.getProperty("db.username"), properties.getProperty("db.password"));
        //返回一个连接对象
        return connection;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我没有好昵称

一介凡夫,心有所念,成就自己。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值