MySQL的创建
1.打开HeidiSQL
2.选项都为默认,输入密码,点击打开.
3.新建一个名字为restaurant的数据库,点击确定
4.右键数据库,选择创建新的➡表,名字为user
点击保存,
表user就建立完成
使用JAVA查询MySQL
1.在pom.xml中添加,点击Maven的刷新按钮
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2.在com,.sdcet下新建一个包mapper
3.在mapper包下新建一个接口UserMapper,添加以下代码
package com.sdcet.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT `name` FROM user WHERE id = #{id}")
public String selectNameById(long id);
}
4.在rescourcs下新建一个file的yml文件
添加以下代码
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/restaurant?serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
5.在controller下新建一个UserController类
并添加如下代码
package com.sdcet.controller;
import com.sdcet.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/getName")
public String getName(Long id){
return userMapper.selectNameById(id);
}
}
6.运行Maven,
输入http://127.0.0.1:8080/getName?id=2这样就可以查询数据库