制作人:全心全意
引入依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>
新建application.yml文件(resources中)
spring: datasource: ## spring2 多数据源读取名称存在bug(使用jdbc-url) url: jdbc:mysql://172.16.1.12:3306/test?useSSL=false username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver
创建Service
package com.zq.mysql.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private JdbcTemplate jdbcTemplate; public boolean addUser(String userName, Integer age) { int update = jdbcTemplate.update("insert into users values(null,?,?)", userName, age); return update > 0 ? true : false; } }
创建测试接口
package com.zq.mysql.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @Autowired private UserService userService; @RequestMapping("/addUser") public String addUser(String userName, Integer age) { return userService.addUser(userName, age) == true ? "success" : "no"; } }
原文:https://www.cnblogs.com/zhangquan-yw/p/14173279.html