Mapleyang

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

编写配置文件(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";
    }
}
复制代码

 

posted on   折木~  阅读(148)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
 
点击右上角即可分享
微信分享提示