我是靠谱客的博主 诚心火,最近开发中收集的这篇文章主要介绍springboot和数据库JDBC连接,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

依赖:

<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

配置数据库连接信息:

spring:
datasource:
username: root
password: root
# 报错: The server time zone value xxx is unrecognized or 需配置时区 &serverTimezone=UTC
url: jdbc:mysql://localhost:3306/stu?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver

配置Controller

@RestController
public class JdbcController {
@Autowired//注入springboot配置好的模板
private JdbcTemplate jdbcTemplate;
@RequestMapping("/queryAll")
public List<Map<String,Object>> queryAll(){
String sql = "select * from peoper";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
@RequestMapping("/add")
public String add(){
String sql = "insert into stu.peoper (name, age) values (?,?);";
Object[] objects = new Object[2];
objects[0]="啾啾";
objects[1]="19";
jdbcTemplate.update(sql,objects);
return "add-ok";
}
@RequestMapping("/update/{id}")
public String update(@PathVariable("id") int id){
String sql = "update stu.peoper set name = ?,age = ? where id = "+id;
Object[] objects = new Object[2];
objects[0]="呜呜";
objects[1]="20";
jdbcTemplate.update(sql,objects);
return "update-ok";
}
@RequestMapping("/delete/{id}")
public String delete(@PathVariable("id") int id){
String sql = "delete from stu.peoper where id = ?;";
jdbcTemplate.update(sql,id);
return "delete-ok";
}
}

最后

以上就是诚心火为你收集整理的springboot和数据库JDBC连接的全部内容,希望文章能够帮你解决springboot和数据库JDBC连接所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部