JdbcTemplate基本使用

JdbcTemplate概述

它是spring框架中提供的一个对象,是对原始繁琐的JdbcAPI对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和MbernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。

JdbcTemplate开发步骤

① 导入spring-jdbc和spring-tx坐标

② 创建数据库表和实体

③ 创建JdbcTemplate对象

④ 执行数据库操作

JdbcTemplate基本使用_第1张图片

@Test
    // 测试JdbcTemplate的开发步骤
    public void test2() throws PropertyVetoException {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);
        int row = jdbcTemplate.update("insert into account values(?, ?)", "lisi11", 1000);
        System.out.println(row);
    }

//-----------------------------------------------------






    


    
        
        
        
        
    


    
        
    



//----------------------------------------------

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=1234

 JdbcTemplate基本使用-常用操作-更新删除操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testUpdate(){
        jdbcTemplate.update("update account set money = ? where name = ?",10001, "wangwu");
    }

    @Test
    public void testDelete(){
        jdbcTemplate.update("delete from account where money = ?", 10001);
    }
}

 JdbcTemplate基本使用-常用操作-查询操作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testUpdate(){
        jdbcTemplate.update("update account set money = ? where name = ?",10001, "wangwu");
    }

    @Test
    public void testDelete(){
        jdbcTemplate.update("delete from account where money = ?", 10001);
    }

    //查询多个
    @Test
    public void estQuery(){
        List accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper(Account.class));
        System.out.println(accountList);
    }

    //查询一个
    @Test
    public void testQueryOne(){
        List accountList = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper(Account.class), "lisi");
        System.out.println(accountList);

    }

    //聚合查询
    @Test
    public void testQueryCount(){
        Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
        System.out.println(count);
    }
}

你可能感兴趣的:(java,开发语言)