十九 Spring的JDBC模版使用: 模版的CRUD的操作

Spring的JDBC模版使用: 模版的CRUD的操作

  • 保存操作
  • 修改操作
  • 删除操作
  • 查询操作
import com.ithheima.jdbc.domian.Account;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcDemo2 {
    @Resource(name="jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Test
    //保存操作
    public void demo1(){
        jdbcTemplate.update("insert into account values(null,?,?)", "菊花花1",1000d);
    }
    @Test
    //修改操作
    public void demo2(){
        jdbcTemplate.update("update account set name=?,money=? where id = ?", "菊花",10000d,5);
    }
    @Test
    //删除操作
    public void demo3(){
        jdbcTemplate.update("delete from account where id = ?", 6);
    }
    @Test
    //查询操作
    public void demo4(){
    String name = jdbcTemplate.queryForObject("select name from account where id = ?", String.class,5);
    System.out.println(name);
    }
    @Test
    //统计查询
    public void demo5(){
    Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
    System.out.println(count);
    }
    
    @Test
//    封装到一个对象中
    public void demo6(){
        Account account = jdbcTemplate.queryForObject("select * from account where id= ?",new MyRowMapper(),5 );
        System.out.println(account);
    }
    @Test
    //查询多条记录
    public void demo7(){
        List<Account> list = jdbcTemplate.query("select * from account", new MyRowMapper());
        for (Account account : list) {
            System.out.println(account);
        }
    }
            
       //数据封装              
    class MyRowMapper implements RowMapper<Account>{
        @Override
        public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
            Account account = new Account();
            account.setId(rs.getInt("id"));
            account.setName(rs.getString("name"));
            account.setMoney(rs.getDouble("money"));
            return account;
        }        
    }
}

实体类:

猜你喜欢

转载自www.cnblogs.com/ltfxy/p/9891528.html