创建一个 JdbcService,并通过 Spring Boot 直接运行 SQL
- 前言
- 1. 环境准备
- 1.1 依赖配置
- 1.2 配置文件
- 2. 创建 `JdbcService`
- 2.1 定义 `JdbcService`
- 2.2 使用 `JdbcService`
- 3. 运行示例
- 3.1 创建表
- 3.2 插入数据
- 3.3 查询数据
- 3.4 更新数据
- 3.5 删除数据
- 4. 安全性注意事项
- 5. 总结
前言
在 Spring Boot 中,使用 JDBC 直接运行 SQL 是一种常见的操作,尤其是在需要执行原生 SQL 或复杂查询时。下面是一个完整的示例,展示如何创建一个 JdbcService
,并通过 Spring Boot 直接运行 SQL。
1. 环境准备
1.1 依赖配置
在 pom.xml
中添加以下依赖:
<dependencies><!-- Spring Boot Starter JDBC --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- 数据库驱动(以 MySQL 为例) --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- Spring Boot Starter Web(可选,用于创建 REST API) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>
1.2 配置文件
在 application.properties
中配置数据库连接信息:
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2. 创建 JdbcService
2.1 定义 JdbcService
创建一个 JdbcService
类,用于执行 SQL 语句。我们将使用 Spring 的 JdbcTemplate
来简化 JDBC 操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Map;@Service
public class JdbcService {@Autowiredprivate JdbcTemplate jdbcTemplate;/*** 执行查询 SQL,返回结果列表** @param sql SQL 语句* @return 查询结果(每行数据以 Map 形式存储)*/public List<Map<String, Object>> query(String sql) {return jdbcTemplate.queryForList(sql);}/*** 执行更新 SQL(如 INSERT、UPDATE、DELETE)** @param sql SQL 语句* @return 受影响的行数*/public int update(String sql) {return jdbcTemplate.update(sql);}/*** 执行任意 SQL 语句** @param sql SQL 语句*/public void execute(String sql) {jdbcTemplate.execute(sql);}
}
2.2 使用 JdbcService
在控制器或服务中注入 JdbcService
,并调用其方法执行 SQL。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.Map;@RestController
public class JdbcController {@Autowiredprivate JdbcService jdbcService;/*** 查询接口** @param sql SQL 查询语句* @return 查询结果*/@GetMapping("/query")public List<Map<String, Object>> query(@RequestParam String sql) {return jdbcService.query(sql);}/*** 更新接口** @param sql SQL 更新语句* @return 受影响的行数*/@GetMapping("/update")public int update(@RequestParam String sql) {return jdbcService.update(sql);}/*** 执行任意 SQL 接口** @param sql SQL 语句* @return 执行结果*/@GetMapping("/execute")public String execute(@RequestParam String sql) {jdbcService.execute(sql);return "SQL 执行成功";}
}
3. 运行示例
3.1 创建表
在数据库中创建一个测试表:
sql">CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(50),age INT
);
3.2 插入数据
通过 /update
接口插入数据:
curl "http://localhost:8080/update?sql=INSERT INTO users (name, age) VALUES ('Alice', 25)"
curl "http://localhost:8080/update?sql=INSERT INTO users (name, age) VALUES ('Bob', 30)"
3.3 查询数据
通过 /query
接口查询数据:
curl "http://localhost:8080/query?sql=SELECT * FROM users"
输出结果:
[{"id": 1, "name": "Alice", "age": 25},{"id": 2, "name": "Bob", "age": 30}
]
3.4 更新数据
通过 /update
接口更新数据:
curl "http://localhost:8080/update?sql=UPDATE users SET age = 26 WHERE name = 'Alice'"
3.5 删除数据
通过 /update
接口删除数据:
curl "http://localhost:8080/update?sql=DELETE FROM users WHERE name = 'Bob'"
4. 安全性注意事项
直接运行用户输入的 SQL 语句存在 SQL 注入风险。在实际生产环境中,应避免直接执行用户输入的 SQL。可以通过以下方式增强安全性:
-
使用参数化查询:
- 使用
JdbcTemplate
的query
或update
方法时,传入参数列表,而不是直接拼接 SQL。
jdbcTemplate.query("SELECT * FROM users WHERE name = ?", new Object[]{"Alice"}, (rs, rowNum) -> {// 处理结果集 });
- 使用
-
限制 SQL 类型:
- 只允许执行 SELECT 查询,禁止执行 UPDATE、DELETE 等写操作。
-
权限控制:
- 确保数据库用户只有必要的权限(如只读权限)。
5. 总结
通过 Spring Boot 和 JDBC,我们可以轻松实现直接运行 SQL 的功能。JdbcTemplate
提供了强大的工具来简化 JDBC 操作,但需要注意安全性问题,避免 SQL 注入风险。如果需要更复杂的 ORM 功能,可以考虑使用 JPA 或 MyBatis。