基于上次一版本的代码,本篇只添加需要添加的代码
1、添加maven依赖
<!-- 数据库依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、创建UserService接口和实现类
public interface UserService {
Integer getUserCount();
}
package com.zh.SpringBootDemo.service.imp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.zh.SpringBootDemo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer getUserCount() {
return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
}
}
3、在配置文件“application.properties”添加数据的链接信息
spring.datasource.url=jdbc:mysql://192.168.2.111:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
完成!