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";
    }
相关推荐
桦说编程13 分钟前
Java 中如何创建不可变类型
java·后端·函数式编程
IT毕设实战小研16 分钟前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi39 分钟前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
一只爱撸猫的程序猿1 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
天宇_任1 小时前
Mysql数据库迁移到GaussDB注意事项
数据库·mysql·gaussdb
甄超锋1 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
阿华的代码王国2 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
Jimmy2 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
AntBlack2 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
bobz9653 小时前
pip install 已经不再安全
后端