抽离配置文件

HeJin小于 1 分钟数据库技术JDBC

jdbc.properties

driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&&useSSL=false&serverTimezone=GMT%2B8
username=root
password=root

Properties类加载配置文件

@Test
public void test4() throws SQLException, ClassNotFoundException, IOException {
    // 1.定义要素
    Properties properties = new Properties();
    properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
    String driverName = properties.getProperty("driverName");
    String url = properties.getProperty("url");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");

    // 2.加载驱动,实例化驱动。并注册驱动
    // 仅仅需要jvm加载一下
    Class.forName(driverName);

    // 4.获取连接
    Connection connection = DriverManager.getConnection(url, username, password);

    System.out.println(connection);
}