SpringBoot+jdbcTemplate连接MySQL

SpringBoot利用jdbcTemplate连接数据库

1.导入依赖包

xml 复制代码
  <dependency>
     <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jdbc</artifactId>
  </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <scope>runtime</scope>
  </dependency>

2.配置数据库连接

yml 复制代码
spring:
  datasource:
     driver-class-name: com.mysql.cj.jdbc.Driver
     url: jdbc:mysql:///user
     username: root
     password: root

3.在类中注入JdbcTemplate

java 复制代码
    @Autowired
    private JdbcTemplate jdbcTemplate;

利用JdbcTemplate实现创建表:

java 复制代码
// 使用jdbcTemplate创建表
    @GetMapping("createTable")
    public String createTable() {
        String sql=
                "CREATE TABLE `student`(\n"+
                    "`id` INT(11) NOT NULL,\n"+
                    "`student_name` VARCHAR(20) NOT NULL,\n"+
                    "`student_age` INT(11) NOT NULL,\n"+
                        "PRIMARY KEY (`id`)\n"+
                ") ENGINE=InnoDB;";
        jdbcTemplate.execute(sql);
        return "success";
    }

插入数据:

java 复制代码
 //使用jdbcTemplate保存数据
    @GetMapping("saveStudent")
    public String saveStudent() {
        String sql=
                "insert into student(id,student_name,student_age) values(2,'xiaoh',25)";
        jdbcTemplate.update(sql);
        return "success";
    }

更新数据:

java 复制代码
//使用jdbcTemplate修改数据
    @GetMapping("updateStudent")
    public String updateStudent(int id,String student_name) {
        String sql=
                "update student set student_name=? where id=?";
        jdbcTemplate.update(sql,student_name,id);
        return "success";
    }

删除数据:

java 复制代码
 //使用jdbcTemplate删除数据
    @GetMapping("deleteStudent")
    public String deleteStudent(int id) {
        String sql=
                "delete from student where id=?";
        jdbcTemplate.update(sql,id);
        return "success";
    }
相关推荐
JELEE.8 分钟前
Django中的clean()方法和full_clean()方法
后端·python·django
aiopencode9 分钟前
iOS 上架工具全解析,从 Xcode 到 开心上架(Appuploader)跨平台命令行免 Mac 上传指南
后端
爱分享的鱼鱼11 分钟前
Java基础(六:线程、线程同步,线程池)
java·后端
敖云岚19 分钟前
【疑难解答】MySQL 报错 Public Key Retrieval is not allowed
数据库·mysql
申阳22 分钟前
Day 8:06. 基于Nuxt开发博客项目-我的服务模块开发
前端·后端·程序员
quant_198625 分钟前
全面解析美股行情API
经验分享·后端·python·websocket·程序人生·区块链
半部论语1 小时前
MyBatis-Plus 通用 CRUD 实现原理技术文档
java·spring boot·mybatis
手握风云-1 小时前
JavaEE 进阶第六期:Spring Boot 如何重塑后端开发
java·spring boot·java-ee
databook1 小时前
数据分析师的基本功总结
后端·数据分析·求职
Deamon Tree1 小时前
【设计题】如何实现一个线程安全的缓存?
java·spring boot·spring