编写配置文件(application.yml)
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/mybatis?useUnicode&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
测试连接
@SpringBootTest class Springboot04DataApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { //查看一下默认的数据源 System.out.println(dataSource.getClass()); //获得数据库连接 Connection connection = null; try { connection = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } System.out.println(connection); //关闭 connection.close(); } }
查询数据库的数据
增删改查
package com.maple.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class JDBCController { //自动配置JdbcTemplate @Autowired JdbcTemplate jdbcTemplate; //查询数据库的所有信息 //没有实体类,数据库中的东西,怎么获取?Map @GetMapping("/userList") public List<Map<String, Object>> userList(){ String sql = "select * from user"; List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql); return list_maps; } //添加一个信息 @GetMapping("/addUser") public String addUser(){ String sql = "insert into mybatis.user(id,name,pwd) values(4,'烟雨如花','123456')"; jdbcTemplate.update(sql); return "updata-ok"; } //添加一个信息 @GetMapping("/updateUse/{id}") public String updateUser(@PathVariable int id){ String sql = "update mybatis.user set name = ?,pwd = ? where id = "+id; //封装 Object[] objects = new Object[2]; objects[0] = "赤色夫人"; objects[1] = "123456"; jdbcTemplate.update(sql,objects); return "updateUse-ok"; } //添加一个信息 @GetMapping("/delectUser/{id}") public String delectUser(@PathVariable int id){ String sql = "delete from mybatis.user where id=?"; jdbcTemplate.update(sql,id); return "delectUser-ok"; } }
原文地址:https://www.cnblogs.com/Mapleyang/p/16578228.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。