SpringBoot-JDBC

1. Create projects

2. Configure the project

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/ssmbuild? useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver
Copy the code

Pay attention to the name of key!!

Under test:

package com.gip;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class SpringbootJdbcApplicationTests {

    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads(a) throws SQLException {
        / / check the default data source class com. Zaxxer. Hikari. HikariDataSource
        System.out.println(dataSource.getClass());

        // Get the database connection
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        // Close the connectionconnection.close(); }}Copy the code

No problem with connection

3. Query the database

New JDBController. Java

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

import java.util.List;
import java.util.Map;
@RestController
public class JDBController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql= "select * from mybatis.user";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        returnlist; }}Copy the code

Idea Connect to the database first

His default time zone is UTC.

Into Asia/Shanghai

Go to http://localhost:8080/userList

4. Insert data

The new method

  @GetMapping("/add")
    public String add(a){
        String sql= "insert into mybatis.user(id,name) values(4,'ggggip')";
        jdbcTemplate.update(sql);
        return "insert ok!";
    }
Copy the code

access