使用配置文件写JDBC

1.jdbc.properties

msg1=com.mysql.cj.jdbc.Driver //JDBC 驱动类的全名

msg2=jdbc:mysql://localhost:3306/数据库名?serverTimezone=GMT

msg3=root //数据库用户名

msg4=123456 //数据库密码

2.测试类

java 复制代码
public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
        //创建一个 Properties 对象,用于存储配置信息。
        Properties properties = new Properties();

        //使用 ClassLoader 获取名为 jdbc.properties 的资源文件的输入流。这个文件应位于项目的类路径下。
        InputStream inputStream = Test01.class.getClassLoader().getResourceAsStream("jdbc.properties");

        //调用 load 方法将文件中的键值对加载到 properties 对象中。
        properties.load(inputStream);

        String driver = properties.getProperty("msg1");
        String url = properties.getProperty("msg2");
        String name = properties.getProperty("msg3");
        String pwd = properties.getProperty("msg4");
        
        //动态加载指定的 JDBC 驱动。这样可以在运行时注册该驱动。
        Class.forName(driver);
        
        //DriverManager.getConnection(url, name, pwd):根据提供的 URL、用户名和密码获取数据库连接。   
        Connection root = DriverManager.getConnection(url, name, pwd);
        System.out.println(root);

    }
}
相关推荐
徐小黑ACG2 分钟前
Redis-基础
数据库·redis·缓存
火山引擎开发者社区14 分钟前
案例实践 | 让 Agent 读懂业务口径:ContextSearch 在广告数据查询中的实践
数据库
学长毕设1 小时前
基于SpringBoot的野生动物公益保护平台设计与实现-附源码
java·spring boot·后端
10年前端老司机2 小时前
Milvus 8种检索能力实践
数据库·python·agent
aiks_yuan2 小时前
MySQL 深分页 LIMIT 越翻越慢怎么办:300 万行实测 OFFSET、延迟关联和 keyset 的耗时差距(MySQL 8.2)
mysql
Decay__2 小时前
14_MySQL 高可用与容灾架构 —— MGR / InnoDB Cluster / Keepalived+VIP / 双主 / 读写分离 / 两地三中心
运维·数据库·sql·mysql·架构
SL_staff2 小时前
离散制造排程破局:JVS-APS 四步闭环落地实践(开发者视角)
java·产品·全栈
freejackman2 小时前
【实战三】撕开脱敏盲区:深度解析 CASE WHEN 与窗口函数血缘
大数据·数据库·sql
这个昵称不容易2 小时前
SpringBoot 美容院管理系统:232个Java文件315个接口,5套角色从预约到发货一整条链路
java·springboot·毕设
装不满的克莱因瓶3 小时前
【SpringAI Alibaba】ReactAgent记忆管理MessageTrimmingHook与MessageDeletionHook
java·人工智能·ai·ai编程·springai·springaialibaba