SpringBoot整合JDBC练习使用

SpringBoot整合JDBC练习使用

一、引入JDBC依赖和Mysql数据库驱动

		<!--jdbc依赖-->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--MySQL-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

二、配置数据库数据源

创建application.yml文件,并输入以下配置

spring:
  datasource:
    username: root
    password: mysql
    #假如时区报错,就添加一个时区的配置: serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

三、接口

package com.example.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;

/**
 * JDBC练习使用
 * @author  桃味果仁
 */
@RestController
public class JDBCController {
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //没有实体类,数据库中的数据怎么获取? 使用map

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
    
    
        String sql = "select * from user";
        List<Map<String, Object>> mapsList = jdbcTemplate.queryForList(sql);
        return mapsList;
    }

    /**
     * 添加用户
     * @return
     */
    @GetMapping("/addUser")
    public String addUser(){
    
    
        String sql = "insert into user(username, sex) values ('乐乐', '女')";
        jdbcTemplate.execute(sql);
        return "is ok";
    }

    /**
     * 更新用户
     * @param id
     * @return
     */
    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
    
    
        String sql = "update user set username=?, sex=? where id="+id;
        Object[] para = new Object[2];
        para[0] = "呵呵";
        para[1] = "女";
        int update = jdbcTemplate.update(sql, para);
        return "updateUser ok" + update;
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
    
    
        String sql = "delete from user where id=?";
        int update = jdbcTemplate.update(sql, id);
        return "deleteUser ok" + update;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43742217/article/details/121257231