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";
    }
相关推荐
考虑考虑41 分钟前
JDK26中的Map.ofLazy
java·后端·java ee
云浪2 小时前
Go 并发实战:从零实现一个高并发安全的任务调度器
javascript·后端·go
苏三的开发日记2 小时前
Docker 启动顺序优化(CentOS / Ubuntu)
后端
高频因子挖掘机4 小时前
同一交易日出现重复 K 线:去重前先确认时间、来源和粒度
后端·github·api
feely02085 小时前
《我写了 31 个静态扫描插件,踩了 7 个「假绿」》
后端
橙子家6 小时前
参数校验类异常(Argument Exception)【C# Exception 详解系列一】
后端
掘金挖土6 小时前
前端手摸手跑路之 AI 应用开发(九)
前端·后端
这个DBA有点耶6 小时前
从症状到根因:数据库监控指标的分层方法与静态/动态阈值策略
数据库·mysql·代码规范
全栈弄潮儿7 小时前
Python实战第8期:函数
后端·python·编程语言