使用JdbcTemplate操作数据库

55 阅读1分钟

1. 导入相关坐标

<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <version>8.0.33</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.2.16</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.2.20.RELEASE</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13</version>
  <scope>test</scope>
</dependency>

2. 基础使用

public static void main(String[] args) {
    JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());
    List<Account> accountList = template.query("select * from account", new BeanPropertyRowMapper<>(Account.class));
    for (Account account : accountList) {
        System.out.println(account);
    }
}

3. 具体增删改查用法

public class AppTest {

    private static JdbcTemplate jdbcTemplate;

    @BeforeClass
    public static void before(){
        jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
    }


    // 添加
    @Test
    public void insert(){
        String sql = "insert into account(name, money) VALUES (?,?)";
        Account account1 = new Account();
        account1.setName("迪迦");
        account1.setMoney(10000.0);
        jdbcTemplate.update(sql, account1.getName(), account1.getMoney());
        find();
    }

    // 删除
    @Test
    public void delete(){
        String sql = "delete from account where id = ?";
        int i = jdbcTemplate.update(sql, 6);
        System.out.println(i);
    }

    // 更新
    @Test
    public void update(Account account) {
        String sql = "update account set name = ?,money = ? where id = ?";
        int i = jdbcTemplate.update(sql, account.getName(), account.getMoney(), account.getId());
        System.out.println(i);
    }

    // 查询所有
    @Test
    public void find(){
        List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<>(Account.class));
        for (Account account : accountList) {
            System.out.println(account);
        }
    }

    // 查询一个bean
    @Test
    public void findByName(String name) {
        String sql = "select * from account where name = ?";
        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), name);
        System.out.println(account);
    }

    // 查询一个Object
    @Test
    public void findOne(){
        String sql = "select count(id) from account";
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(integer);
    }
}