通过JDBC可以直接使用Java编程来操作数据库。
本章以MySQL为例介绍spring boot使用JDBC操作MySQL数据库。
JDBC依赖配置
新建项目,在pom文件中加入JDBC依赖和Mysql依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.28</version>
</dependency>
在resources中propertie中的配置数据库信息。
使用默认端口为3306,数据库名称为testdb。
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
## DBname=testdb
## database username
spring.datasource.username=root
## database password
spring.datasource.password=your_password
## database driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
创建实体类
创建一个实体类,用作表数据,这里省略set,get方法。
public class User {
private int id;
private String user_name;
private String user_password;
public User(int id, String user_name, String user_password) {
this.id = id;
this.user_name = user_name;
this.user_password = user_password;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
使用Controller测试
新建一个UserController,加入@RestController注解,在UserController内注入jdbcTemplate。
@RestController
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
......
}
数据库操作方法基本上是create,update,retrieve,delete 4种
jdbcTemplate操作数据库基本上分为3种方法:
1.execute方法:
在UserController类中添加新建数据表的方法。
@GetMapping("createTable")//网页地址
public String createTable() {//execute方法
String sql =
"CREATE TABLE user(\n" +
"id int(11) NOT NULL AUTO_INCREMENT,\n" +
"user_name varchar(255) NOT NULL,\n"+
"user_password varchar(255) DEFAULT NULL,\n"+
"PRIMARY KEY(id)\n"+
") ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;";//列名和表名不需要单引号!!!
jdbcTemplate.execute(sql);
return "创建User表成功!";
}
启动项目,在浏览器访问:http://localhost:8080/createTable
显示成功。数据库中输入 show tables;显示表以及创建成功。
update方法
创建方法saveUserSql,直接执行一个插入语句。
@GetMapping("saveUserSql")//update方法
public String saveUserSql(){
String sql="insert into user(user_name,user_password) values('dalao','123')";
int rows=jdbcTemplate.update(sql);
return "执行成功,影响"+rows+"行。";
}
重启项目,在浏览器中可以看到.
接着写增删改方法。
//新增方法
@GetMapping("saveUser")
public String saveUser(String userName,String password){
int rows=jdbcTemplate.update("insert into user(user_name,user_password) values(?,?)",userName,password);
return "执行成功,影响"+rows+"行。";
}
//修改方法
@GetMapping("updateUserPassword")
public String updateUserPassword(int id,String password){
int rows=jdbcTemplate.update("UPDATE user set user_password=? where id=?",password,id);
return "执行成功,影响"+rows+"行。";
}
//删除方法
@GetMapping("deleteUserById")
public String deleteUserById(int id){
int rows=jdbcTemplate.update("delete from user where id=?" ,id);
return "执行成功,影响"+rows+"行。";
}
jdbc中提供了批处理方法batchUpdate,可以传入SQL和一个批处理的数组。下面的方法可以插入10条数据。
//批量插入数据方法
@GetMapping("batchSaveUserSql")
//http://localhost:8080/batchSaveUserSql
public String batchSaveUserSql(){
String sql=
"insert into user(user_name,user_password) values (?,?)";
List<Object[]> paramList=new ArrayList<>();
for(int i=0;i<10;i++){
String[] arr=new String[2];
arr[0]="zhangsan"+i;
arr[1]="lisi"+i;
paramList.add(arr);
}
jdbcTemplate.batchUpdate(sql,paramList);
return "批量操作更新成功!";
}
在浏览器上输入地址,显示操作成功。
query方法
query方法是有关查询的方法。
创建getUserByUserName方法,用到实体类User,查询一个列表。
//查询一个列表方法
@GetMapping("getUserByUserName")
//http://localhost:8080/getUserByUserName?userName=zhangsan()
public List getUserByUserName(String userName){
String sql="select * from user where user_name=?";
List<User> list=jdbcTemplate.query(sql,new Object[]{userName},new BeanPropertyRowMapper<>(User.class));
return list;
}
重启项目,在浏览器上输入:
http://localhost:8080/getUserByUserName?userName=zhangsan0
得到结果如图所示:
使用一个返回Map的方法queryForMap。
//查询一个MAP方法
@GetMapping("getMapById")
public Map getMapById(Integer id){
String sql="select * from user where id=?";
Map map=null;
try {
map = jdbcTemplate.queryForMap(sql, id);
}catch(EmptyResultDataAccessException e){
return null;
}
return map;
}
在浏览器访问:
http://localhost:8080/getMapById?id=8,结果如下所示:
查询一个数据库不存在的数据,在浏览器输入:http://localhost:8080/getMapById?id=80,页面显示为空白,因为返回了null。