关于Springboot 整合 JdBC
1. 新建一个项目,命名为,SpringBoot-data
勾选相关依赖,因为我们想要实现和数据库相连接,所以需要jdbc Api 和 MysqlDriver
2. 在resource目录下新建application.yaml
application.yaml 里面是写关于连接的配置的
spring:
datasource:
username: root #注意是username!!!!
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
ps:一定要注意是username 和 password 以及后面的账号和密码一定别写错了!!!!
这就是你写错时候的报错 : Access denied for user ‘zhen’@‘Localhost’ (using password: YES)
3. 编写测试文件 测试能否连接
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认数据源
System.out.println(dataSource.getClass());
//获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
然后 : 我们可以看到他默认给我们配置的数据源为 :
class com.zaxxer.hikari.HikariDataSource
再然后我们全局搜索,找到了数据源的所有自动配置都在 :这个DataSourceAutoConfiguration文件:
@Import(
{Hikari.class, Tomcat.class, Dbcp2.class, Generic.class, DataSourceJmxConfiguration.class}
)
protected static class PooledDataSourceConfiguration {
protected PooledDataSourceConfiguration() {
}
}
我们现在有了数据库连接,就可以 CRUD 操作数据库了。
小知识 :
xxx Template : Springboot 已经配置好了模版 bean 拿来即用就好
在这里 我们需要用 JDBC Template
4. 相关JDBC CRUD 操作
-
建立controller层 并编写 JdbcController 类
-
编写JdbcController类 实现增删改查
@RestController public class JdbcController { @Autowired JdbcTemplate jdbcTemplate; //查询数据库的所有信息 //我们没写数据库 ,用map接受信息 @GetMapping("userList") public List<Map<String, Object>> toUserList() { String sql = "select * from user"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } //增加一个数据 @GetMapping("/addList") public String addUser() { String sql = "insert into user(id, name, pwd) VALUES (7,'ssb','123456')"; jdbcTemplate.update(sql); return "add-OK"; } //修改一个数据 @GetMapping("/updateList/{id}") public String updateUser(@PathVariable("id") int id) { String sql = "update user set name=?,pwd=? where id=" + id; //将预编译的封装对象中 Object[] objects = new Object[2]; objects[0] = "sb3"; objects[1] = "123456"; jdbcTemplate.update(sql, objects); //注意这里需要插入两个数据 return "update-OK"; } //删除一个数据 @GetMapping("/delList/{id}") public String deleteUser(@PathVariable("id") int id) { String sql = "delete from user where id=?"; jdbcTemplate.update(sql, id); return "del-OK"; } }
相关问题:
-
在这里 我们没有启用事务 但是发现上面写的方法都能提交到数据库,改变数据库的内容,因此发现JdbcTemplate 帮我们启用了事务
-
在写查询数据库信息方法时候,我们并没有写实体类 ,但还是想实现这个操作的话,我们可以使用万能的map
List<Map<String, Object>>