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";
    }
相关推荐
csdn_aspnet1 小时前
Docker MySql 5.7、MySql8.x 进阶配置
mysql·docker·容器
Csvn3 小时前
Nginx 静态站点与 location 匹配:优先级、alias、缓存头与 gzip
后端·nginx
小满zs3 小时前
Go语言第二十章(初探Gin)
后端·go
学长毕设3 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
小满zs3 小时前
Go语言第十九章(http标准库)
后端·go
考虑考虑5 小时前
nginx拦截url
运维·后端·nginx
GISer_Jing6 小时前
GitHub热点I
后端·ai·langchain
谭光志6 小时前
如何让 AI 高效工作
前端·后端·ai编程
ServBay7 小时前
连AI自己也不愿意维护自己的屎山代码
后端·ai编程·claude
code2cat7 小时前
【随笔】MCP长任务:查询已经返回,为什么任务还没有完成
javascript·人工智能·后端·mcp