详解SpringBoot封装使用JDBC Spring Boot中可以在配置文件中直接进行数据库配置, spring.datasource.username= root spring.datasource.password= 123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=truecharacterEncoding=utf-8 spring.datasource.driver-class-name=co
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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
沃梦达教程
本文标题为:详解SpringBoot封装使用JDBC
猜你喜欢
- Java中的日期时间处理及格式化处理 2023-04-18
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- Java实现顺序表的操作详解 2023-05-19
- JSP页面间传值问题实例简析 2023-08-03
- JSP 制作验证码的实例详解 2023-07-30
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- 深入了解Spring的事务传播机制 2023-06-02
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06