1.连接配置
首先引入数据库驱动:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
以mysql8.0版本为例,数据库连接程序编写如下:
@Test
public void test() throws ClassNotFoundException, SQLException, IOException {
// 读取配置文件中信息(读取类路径下配置)
InputStream is = TestClass.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
System.out.println(properties);
System.out.println(properties.getProperty("driverClass"));
// driverClass=com.mysql.cj.jdbc.Driver
// url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimeZone=UTC
Class.forName(properties.getProperty("driverClass"));
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
Driver在静态代码块中有所配置,当加载此类时,会自动进行注册