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";
    }
相关推荐
Marst Code3 分钟前
(Django)初步使用
后端·python·django
代码之光_198010 分钟前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端
编程老船长22 分钟前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
IT果果日记44 分钟前
DataX+Crontab实现多任务顺序定时同步
后端
苹果醋32 小时前
快速玩转 Mixtral 8x7B MOE大模型!阿里云机器学习 PAI 推出最佳实践
spring boot·nginx·毕业设计·layui·课程设计
程序员大金2 小时前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql
gorgor在码农2 小时前
Mysql 索引底层数据结构和算法
数据结构·数据库·mysql
-seventy-2 小时前
SQL语句 (MySQL)
sql·mysql
姜学迁2 小时前
Rust-枚举
开发语言·后端·rust
爱学习的小健2 小时前
MQTT--Java整合EMQX
后端