当前位置:   article > 正文

创建Maven并且与Mysql连接_mysql数据库如何创建并与maven项目链接

mysql数据库如何创建并与maven项目链接

创建MySQL

1、打开HeidiSQL

2、输入密码 \rightarrow点击开打

3、新建一个名为restaurant的数据库 \rightarrow 点击确定

4、 在restaurant数据库中创建名为user的数据表,并且添加数据 \rightarrow 点击保存

5、数据表创建成功

使用JAVA查询MySQL

1、在Maven中的pom.xml中添加MySQL查询语句 \rightarrow 点击刷新按钮

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>8.0.16</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.mybatis.spring.boot</groupId>
  8. <artifactId>mybatis-spring-boot-starter</artifactId>
  9. <version>2.1.3</version>
  10. </dependency>

2、在com.school下创建一个mapper的包

3、在mapper包下新建一个接口UserMapper,添加以下代码

  1. import org.apache.ibatis.annotations.Mapper;
  2. import org.apache.ibatis.annotations.Select;
  3. @Mapper
  4. public interface UserMapper {
  5. @Select("SELECT `name` FROM user WHERE id = #{id}")
  6. public String selectManmeById(long id);
  7. }

4、在rescourcs下新建一个file的yml文件 \rightarrow 命名为application.yml

5、在.yml中添加以下代码

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://127.0.0.1:3306/restaurant?serverTimezone=Asia/Shanghai
  4. username: root
  5. password: 123456
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. mybatis:
  8. configuration:
  9. map-underscore-to-camel-case: true
  10. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

6、在controller下新建一个UserController类 \rightarrow 并添加如下代码

  1. import com.school.mapper.UserMapper;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. @Controller
  7. @ResponseBody
  8. public class UserController {
  9. @Autowired
  10. private UserMapper userMapper;
  11. @RequestMapping("getName")
  12. public String getName(Long id){
  13. return userMapper.selectManmeById(id);
  14. }
  15. }

7、运行Main \rightarrow 在浏览器中输入“http://127.0.0.1:8080/getName?id=1” \rightarrow 并且运行

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/289898?site
推荐阅读
相关标签
  

闽ICP备14008679号