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

    }
}
相关推荐
橘颂TA1 分钟前
线程池与线程安全:后端开发的 “性能 + 安全” 双维实践
java·开发语言·安全
高溪流3 分钟前
2.Mysql相关概念 及 数据库操作
数据库·mysql
Summer_Uncle8 分钟前
【QT学习】qt项目使用MySQL数据库
数据库·qt·学习
色空大师12 分钟前
服务打包包名设置
java·elasticsearch·maven·打包
施嘉伟13 分钟前
Oracle 10046 Trace 硬核指南:SQL 慢在哪,从底层拉出来
数据库·sql·oracle
xiaoyustudiowww18 分钟前
fetch异步简单版本(Tomcat 9)
java·前端·tomcat
隐退山林22 分钟前
JavaEE:多线程初阶(一)
java·开发语言·jvm
_ziva_28 分钟前
MAC-SQL 多智能体协作框架解析
数据库·oracle
最贪吃的虎28 分钟前
Redis其实并不是线程安全的
java·开发语言·数据库·redis·后端·缓存·lua
一勺菠萝丶30 分钟前
Java 后端想学 Vue,又想写浏览器插件?
java·前端·vue.js