JDBC集成
配置依赖
<!--jdbc依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--
runtime表示被依赖项目无需参与项目的编译,不过后期的测试和运行周期需要其参与。
与compile相比,跳过编译而已,说实话在终端的项目(非开源,企业内部系统)中,
和compile区别不是很大。比较常见的如JSR×××的实现,对应的API jar是compile的,具体实现是runtime的,
compile只需要知道接口就足够了。oracle jdbc驱动架包就是一个很好的例子,一般scope为runtime。
另外runtime的依赖通常和optional搭配使用,optional为true。我可以用A实现,也可以用B实现。
-->
<scope>runtime</scope>
</dependency>
配置yaml文件注入数据源信息
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/lwpstudy?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driverClassName: com.mysql.cj.jdbc.Driver
#更多的配置可看DataSourceProperties类的属性
使用JdbcTemplate实现CRUD
JdbcTemplate常用方法
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
query方法及queryForXXX方法:用于执行查询相关语句;
call方法:用于执行存储过程、函数相关语句。
JdbcTemplate代码参考
@Autowired //获得配置的数据源,可使用原生jdbc进行数据库CRUD操作
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
//新增数据
String addSql="insert into student values(?,?,?,?,?)";
int addStatus = jdbcTemplate.update(addSql, new Object[]{
UUID.randomUUID().toString(), "魔尊", "0", "湖南长沙", 20
});
//删除数据
String delSql="delete from student where stuid=?";
int delStatus = jdbcTemplate.update(delSql, new Object[]{"1"});
//修改数据
String upSql="update student set stuname=?,stuage=? where stuid=?";
int upStatus = jdbcTemplate.update(upSql, new Object[]{
"溪风",22,"cf39cde0-6116-4538-bd94-518a8e9e8396"
});
//查询数据
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from student");
//更多JdbcTemplate可参考官网API:https://docs.spring.io/spring-data/jdbc/docs/2.2.2/api/