本文使用druid连接池和mysql作为演示,springboot默认使用HikariCP连接池
1.引入依赖
<!-- jdbc依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.14</version>
</dependency>
2.修改application.yml配置文件
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
3.使用JdbcTemplate测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MysqlApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testJdbc() {
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from sys_user");
maps.forEach(System.out::println);
}
}
运行输出:
{id=1, username=admin, nickname=admin, sex=1, age=10, email=15222@163.com}
{id=2, username=test, nickname=test, sex=2, age=20, email=test@163.com}
作者公众号