spring框架的JDBC模板技术

自己测试代码(自己来new对象的方式)
public class Demo1 {
    /**
     * 使用new对象方式完成
     */
    @Test
    public void run1(){
        //创建连接池对象,spring框架内置了连接池对象
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        //设置4个参数
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring_db");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        //提供模板,创建对象
        JdbcTemplate template = new JdbcTemplate(dataSource);
        //完成数据的增删改查
        template.update("insert into account values (null,?,?)","熊大",1000);
    }
}
使用Spring框架来管理模板类
编写配置文件


    
    
    
    



    
    
    
    



    
编写测试方法
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")
public class Demo2 {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //增:插入
    @Test
    public void run1(){
        jdbcTemplate.update("insert into account values(null,?,?)","熊二",1200);
    }
    //修改
    @Test
    public void run2(){
        jdbcTemplate.update("update account set name = ?,money=? where id=?","光头强",100,7);
    }
    //删除
    @Test
    public void run3(){
        jdbcTemplate.update("delete from account where id=?",6);
    }
    //通过id查找
    //Jdbc不知道Account类有哪些字段,必须提供一个RowMapper来告诉他如何转换数据
    @Test
    public void run4(){
        Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new BeanMapper(), 5);
        System.out.println(account);
    }

    class BeanMapper implements RowMapper {
        //是一行一行进行数据封装的
        public Account mapRow(ResultSet resultSet, int i) throws SQLException {
            Account account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getDouble("money"));
            return account;
        }
    }
}
Spring框架管理开源的连接池
第一种:纯配置文件


    
    
    
    



    
第二种:将数据库连接的信息配置到属性文件中
属性文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=root
配置文件



    





    
    
    
    



    

你可能感兴趣的:(spring框架,spring,java,后端)