使用配置文件写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);

    }
}
相关推荐
冉冰学姐3 小时前
SSM足球爱好者服务平台i387z(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·ssm 框架·足球爱好者服务平台
大飞记Python3 小时前
部门管理|“编辑部门”功能实现(Django5零基础Web平台)
前端·数据库·python·django
小梁努力敲代码4 小时前
java数据结构--List的介绍
java·开发语言·数据结构
清风6666664 小时前
基于单片机的智能收银机模拟系统设计
数据库·单片机·毕业设计·nosql·课程设计
摸鱼的老谭5 小时前
构建Agent该选Python还是Java ?
java·python·agent
资深低代码开发平台专家5 小时前
PostgreSQL 18 发布
数据库·postgresql
lang201509285 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
夫唯不争,故无尤也5 小时前
Tomcat 启动后只显示 index.jsp,没有进入你的 Servlet 逻辑
java·servlet·tomcat
zz-zjx5 小时前
Tomcat核心组件全解析
java·tomcat
Deschen5 小时前
设计模式-外观模式
java·设计模式·外观模式