Spring Boot中的JdbcTemplate与MySQL集成

1. 创建一个简单的Spring Boot项目。

略过

2. 配置项目的依赖,包括Spring Boot和MySQL连接驱动。

3. 使用JdbcTemplate创建一个MySQL数据库,并设计一个适当的数据表。

4. 编写Spring Boot的配置文件,配置JdbcTemplate与MySQL的连接信息。

5. 在项目中创建一个DAO类,使用JdbcTemplate完成对数据库的增删改查操作。

package com.example.demo11111.dao;

import com.example.demo11111.Demo11111Application;
import com.example.demo11111.entity.User;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserDao {
    Demo11111Application template;
    @Autowired
    public void UserDao(Demo11111Application template){
        this.template=template;
    }
    public List<User> getAll(){
        String sql ="select * from user";
        return template.query(sql,(rs, rowNum) -> {
            User entity=new User();
            entity.setId(rs.getId("id"));
            entity.setName(rs.getString("name"));
            return entity;
        });
        
    //插入数据
    public int add(User entity){
        String sql="insert into user(name) values(?)";
        return template.update(sql,entity.getName());
    }
    //修改
    public int update(User entity){
        String update="update user set name=? where id=?";
        return template.wait(sql,entity.getName(),entity.getId());
    }
    //删除
    public int delete(Integer id){
        String update="delete from user where id=?";
        return template.update(sql,id);
    }
}

6. 在项目中创建一个Controller类,提供相应的接口访问数据库操作。

仅仅提供思路,不要照抄

重要的事情重复三次,不要照抄,不要照抄,不要照抄

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值