SpringBoot 连接 MySQL
- 需要在项目中引入相应的场景启动器,即依赖的jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
- 在项目配置文件中添加数据库连接信息
spring.thymeleaf.cache=false spring.datasource.name=newbee-mall-datasource spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useUnicode=true&serverTimezone=GMT&characterEncoding=utf8&autoReconnect=true&useSSL=false spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456
- 在applicationTest中创建一个测试类datasourceTest来测试一下能否获得与数据库的连接
@RunWith(SpringRunner.class) @SpringBootTest class NewbeeMallApplicationTests { // 注入数据源对象 @Autowired private DataSource defaultDataSource; @Test public void datasourceTest() throws SQLException { //获取数据库连接 Connection connection = defaultDataSource.getConnection(); System.out.print("获取连接:"); //判断对象是否为空 System.out.println(connection != null); connection.close(); } }
对数据库进行简单操作
- 一般开发中,开发者对于数据库的操作通常是基于ORM框架实现的,如MyBatis、Hibernate,或者是直接通过JDBC原生API进行数据库操作,但原生API较为繁琐,Spring Boot 则提供了jdbcTemplate来简化对于数据库的操作
- jdbcTemplate 是spring对于jdbc的封装,也是通过自动配置机制注册到IOC容器中
- 创建一个controller类来实现简单的查询与插入功能
访问以下链接检查正确性@RestController public class JdbcController { //自动配置,可以通过@Autowired注入进来 @Autowired JdbcTemplate jdbcTemplate; //查询所有记录 @GetMapping("/queryAll") public List<Map<String,Object>> queryAll(){ List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from jdbc_test "); return list; } @GetMapping("/insert") public Object insert(String type, String name){ if (StringUtils.isEmpty(type) || StringUtils.isEmpty(name)){ return false; } jdbcTemplate.execute("insert into jdbc_test(type,name) value (\""+ type +"\",\""+ name +"\")"); return true; }
查询:http://localhost:8080/queryAll 新增:http://localhost:8080/insert?type=test&name=测试类