在pom文件中查找有无:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
<plugin> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </plugin>
无就加上,这是mysql的依赖,在application.properties中加入以下配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db3?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456
其中第二行的端口号改成自己的,端口号后面的数据库改为自己本机中存在的数据库,账号密码也是。
查看自己的springboot是否可以正常运行:
点击run 后,在浏览器中输入你相应的URL地址:
比如:
我在带有@Controller的java文件中输入以下代码
@GetMapping("/hello") public String gethello(){ return "hello"; }
在浏览器中输入相应网址:你的本机ip或者localhost:你的端口号/你的@Getmapping的字符
可以成功运行
@Controller public class userdb { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping(value = "/getusers",method = RequestMethod.GET) @ResponseBody public List< Map<String,Object> > getusers(){ String sql="select * from user1"; List<Map<String,Object>> list=jdbcTemplate.queryForList( sql ); return list; } }
代码讲解:
@Controller: 标明此类是controller类,可以对外进行服务,可以接受其他spring容器里的bean
@Autrowired: 自动引入其他包里的类,并创建一个对象
@RequestMapping: 用来处理http请求,value是地址,后面可以跟 get方法,post方法等,当使用get方法时相当于@GetMapping,post相当于@PostMapping
@ResponseBody: 将获取到的数据以json格式展现,不使用该注解是无法在网页面显示出你的mysql里的数据(因为我把这个删了就报错)
String sql ="select * from user1"; 将一串sql语句以string存储起来
jdbcTemplate中的queryList方法可以解析字符串,将其转为数据库中的sql语句,查找出的结果为List形式
于是创建一个list的对象用来保存sql出的结果。
参考文章:
(1条消息) 使用SpringBoot连接MySQL数据库,快速上手_today有点骚的博客-CSDN博客