1.1数据源(连接池)的作用
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/211be6996be7a5d4dd342342721ea986.png)
1.2数据源的手动配置
- 在pom.xml文件中导入要用的jar的坐标
这里测试了两种数据源分别是Druid和c3p0
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
@Test
public void test2() throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC");
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test
public void test1() throws PropertyVetoException, SQLException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String user = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
String jdbcurl = rb.getString("jdbc.url");
dataSource.setDriverClass(driver);
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setJdbcUrl(jdbcurl);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
- 将数据库连接信息与数据库配置解耦,单独创建了一个配置文件保存数据库连接信息.
使用的8版本的mysql数据库连接jar包,所以这里的数据库驱动类有些不同,并且连接URL后面需要指定时区否则会出现问题
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
1.3spring配置数据源