广告
返回顶部
首页 > 资讯 > 后端开发 > Python >详解SpringBoot封装使用JDBC
  • 225
分享到

详解SpringBoot封装使用JDBC

2024-04-02 19:04:59 225人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

Spring Boot中可以在配置文件中直接进行数据库配置, spring.datasource.username= root spring.datasource.passWo

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

在这里插入图片描述


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

在这里插入图片描述

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中有很多template已经写好可以直接拿来用

在这里插入图片描述
在这里插入图片描述


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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解SpringBoot封装使用JDBC

本文链接: https://www.lsjlt.com/news/161172.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作