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

    }
}
相关推荐
神经毒素8 分钟前
WEB安全--Java安全--shiro550反序列化漏洞
java·安全·web安全·shiro
Think Spatial 空间思维14 分钟前
【HTTPS基础概念与原理】TLS握手过程详解
数据库·网络协议·https
hnlucky20 分钟前
Windows 上安装下载并配置 Apache Maven
java·hadoop·windows·学习·maven·apache
逝水如流年轻往返染尘22 分钟前
MySQL表的增删查改
mysql
laowangpython34 分钟前
MySQL基础面试通关秘籍(附高频考点解析)
数据库·mysql·其他·面试
mooyuan天天1 小时前
SQL注入报错“Illegal mix of collations for operation ‘UNION‘”解决办法
数据库·web安全·sql注入·dvwa靶场·sql报错
运维-大白同学1 小时前
go-数据库基本操作
开发语言·数据库·golang
R-sz1 小时前
通过从数据库加载MinIO配置并初始化MinioClient,spring boot之Minio上传
数据库·oracle
forestsea1 小时前
Maven 插件扩展点与自定义生命周期
java·maven
洛阳泰山2 小时前
Windows系统部署MongoDB数据库图文教程
数据库·windows·mongodb