SpringBoot使用JDBC
SpringBoot使用JDBC
一、pom引入jdbc启动器
<!-- jsbc启动器 -->
<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>
二、配置文件配置数据库连接
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# 如果有报时区的异常,添加时区配置即可 serverTimezone=UTC
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: 12345678
三、可以使用原生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.*;
@SpringBootTest
class SpringbootJdbcApplicationTests {
// 注入数据源 dataSource
@Autowired
DataSource dataSource;
// 执行查询语句
@Test
void query() throws SQLException {
Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement();
String sql = "select * from sys_user";
ResultSet rs = stmt.executeQuery(sql);
while (rs != null && rs.next()){
System.out.println("id: " + rs.getInt("id") +
", login_name: " + rs.getString("login_name") +
", usr_name: " + rs.getString("user_name"));
}
stmt.close();
connection.close();
}
// 执行插入语句
@Test
void insert() throws SQLException {
Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement();
String sql = "insert into sys_user(id,user_name,login_name) values(1,'jack','admin')";
stmt.execute(sql);
stmt.close();
connection.close();
}
// 执行修改语句,使用预处理
@Test
void update() throws SQLException {
Connection connection = dataSource.getConnection();
String sql = "update sys_user set user_name=?, login_name=? where id=?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, "Kitty");
pstmt.setString(2, "kkk");
pstmt.setInt(3, 1);
pstmt.execute();
pstmt.close();
connection.close();
}
// 执行删除语句
@Test
void delete() throws SQLException {
Connection connection = dataSource.getConnection();
String sql = "delete from sys_user where id=?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.execute();
pstmt.close();
connection.close();
}
}
四、使用SpringBoot提供的模板类 JdbcTemplate 执行增删改查
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JdbcTestController {
// 注入 JdbcTemplate类
@Autowired
private JdbcTemplate jdbcTemplate;
// 执行查询语句
@RequestMapping("/query")
public List<Map<String, Object>> query(){
String sql = "select * from sys_user";
return jdbcTemplate.queryForList(sql);
}
// 执行插入语句
@RequestMapping("add")
public String add(){
String sql = "insert into sys_user(id,user_name,login_name) values(111,'jsh','ttt')";
jdbcTemplate.update(sql);
return "insert Ok";
}
// 执行修改语句,使用预处理
@RequestMapping("update/{id}")
public String update(@PathVariable Integer id){
String sql = "update sys_user set user_name=?, login_name=? where id=" + id;
jdbcTemplate.update(sql, new Object[]{"aaa", "bbb"});
return "update Ok";
}
// 执行删除语句
@RequestMapping("delete/{id}")
public String delete(@PathVariable Integer id){
String sql = "delete from sys_user where id=?";
jdbcTemplate.update(sql, id);
return "delete Ok";
}
}
五、Druid
Druid 是一个 JDBC 组件库,包含数据库连接池、SQL Parser 等组件。
目前性能最好的两款数据源组件 HiKariCP 和 Druid,相比于HiKariCP,Druid 提供了一套强大的监控特性,通过Druid提供的监控功能,可以清楚知道连接池和SQL的工作情况。
1、pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
2、修改数据源配置
Spring Boot 2.0 以上默认使用 Hikari 数据源,所以配置中我们可以做个更改
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/imooc?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: 12345678
# Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource,这里更改为Druid数据源
type: com.alibaba.druid.pool.DruidDataSource
3、DruidDataSource 配置
spring项目配置
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_user}" />
<property name="password" value="${jdbc_password}" />
<property name="filters" value="stat" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="6000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="20" />
<property name="asyncInit" value="true" />
</bean>
springboot项目配置
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
//配置文件中前缀为 spring.datasource的属性值注入到com.alibaba.druid.pool.DruidDataSource 的同名参数中
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDateSource(){
return new DruidDataSource();
}
}
yaml配置文件中就可以使用下方DruidDataSource配置属性列表中的配置了。
4、DruidDataSource配置属性列表
DruidDataSource配置兼容DBCP,但个别配置的语意有所区别。
配置 | 缺省值 | 说明 |
---|---|---|
name | 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。如果没有配置,将会生成一个名字,格式是:"DataSource-" + System.identityHashCode(this). 另外配置此属性至少在1.0.5版本中是不起作用的,强行设置name会出错。详情-点此处。 | |
url | 连接数据库的url,不同数据库不一样。例如: mysql : jdbc:mysql://10.20.153.104:3306/druid2 oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto | |
username | 连接数据库的用户名 | |
password | 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。详细看这里 | |
driverClassName | 根据url自动识别 | 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName |
initialSize | 0 | 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
maxActive | 8 | 最大连接池数量 |
maxIdle | 8 | 已经不再使用,配置了也没效果 |
minIdle | 最小连接池数量 | |
maxWait | 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 | |
poolPreparedStatements | false | 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 |
maxPoolPreparedStatementPerConnectionSize | -1 | 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 |
validationQuery | 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。 | |
validationQueryTimeout | 单位:秒,检测连接是否有效的超时时间。底层调用jdbc Statement对象的void setQueryTimeout(int seconds)方法 | |
testOnBorrow | true | 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 |
testOnReturn | false | 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 |
testWhileIdle | false | 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 |
keepAlive | false (1.0.28) | 连接池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作。 |
timeBetweenEvictionRunsMillis | 1分钟(1.0.14) | 有两个含义: 1) Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明 |
numTestsPerEvictionRun | 30分钟(1.0.14) | 不再使用,一个DruidDataSource只支持一个EvictionRun |
minEvictableIdleTimeMillis | 连接保持空闲而不被驱逐的最小时间 | |
connectionInitSqls | 物理连接初始化的时候执行的sql | |
exceptionSorter | 根据dbType自动识别 | 当数据库抛出一些不可恢复的异常时,抛弃连接 |
filters | 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall | |
proxyFilters | 类型是List<com.alibaba.druid.filter.Filter>,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系 |
5、Druid内置监控配置
Druid内置提供了一个StatViewServlet用于展示Druid的统计信息。
这个StatViewServlet的用途包括:①提供监控信息展示的html页面;②提供监控信息的JSON API。
注意:使用StatViewServlet,建议使用druid 0.2.6以上版本。
- spring项目一般是通过web.xml文件来配置的
<!-- 配置 Druid 监控信息显示页面 -->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
<init-param>
<!-- 允许清空统计数据 -->
<param-name>resetEnable</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<!-- 用户名 -->
<param-name>loginUsername</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<!-- 密码 -->
<param-name>loginPassword</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
- springboot项目则通过@Configuration方式配置Bean注入
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
//配置文件中前缀为 spring.datasource的属性值注入到com.alibaba.druid.pool.DruidDataSource 的同名参数中
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDateSource(){
return new DruidDataSource();
}
//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
// "/druid/*"配置,内置监控页面的首页是/druid/index.html
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
}
}
访问内置监控页面的首页:例:localhost:8080/druid/index.html
分类:
spring boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?