SpringBoot如何封装使用JDBC

发布时间:2021-12-29 16:43:24 作者:小新
来源:亿速云 阅读:82

这篇文章给大家分享的是有关SpringBoot如何封装使用JDBC的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

Spring Boot中可以在配置文件中直接进行数据库配置,

SpringBoot如何封装使用JDBC

spring.datasource.username= root
spring.datasource.password= 123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

SpringBoot可以直接生成数据库对象
默认数据源为Hikari

SpringBoot如何封装使用JDBC

jdbc连接

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 DataSpringbootApplicationTests {

    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println("默认数据源");
        System.out.println(dataSource.getClass());
        System.out.println("获得数据库连接");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        System.out.println("关闭数据源");
        connection.close();


    }

}

SpringBoot如何封装使用JDBC

springboot中有很多template已经写好可以直接拿来用

SpringBoot如何封装使用JDBC
SpringBoot如何封装使用JDBC

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 {
    @Autowired
    JdbcTemplate jdbcTemplate;
    //查询数据库所有信息
    @GetMapping("/userList")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return  mapList;
    }
    @GetMapping("/addUser")
    public String addUser(){
        String sql = "insert into mybatis.user(id,name,pwd) values (4,'hhh','451651')";
        jdbcTemplate.update(sql);
        return "update-ok";
    }
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from mybatis.user where id = ?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}

SpringBoot如何封装使用JDBC

感谢各位的阅读!关于“SpringBoot如何封装使用JDBC”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. java是怎样封装jdbc的
  2. 如何使用JDBC

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot jdbc

上一篇:如何进行Windows Installer任意文件写入提权漏洞CVE-2021-26415分析

下一篇:C++ OpenCV如何实现身份证离线识别

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》