JdbcTemplate

1.导入jar包

JdbcTemplate

 

 

2.创建JdbcTemplate对象,依赖于数据源DataSource

       JdbcTemplate jt = new JdbcTemplate(new ComboPooledDataSource()); //依赖于数据源DataSource

 

3.调用JdbcTemplate方法来完成CRUD操作

  update();

    String sql = "update t_user set password = ? where id=?";
       jt.update(sql,"111","1");
@Test
    public void test01(){
        String sql = "insert into t_user values(null,?,?)";
        int i = jt.update(sql, "校长", "123");
        System.out.println(i);
    }

  queryForMap();会把查询出来的单个记录封装为map集合

@Test
    public void test03(){
        String sql = "select * from t_user where id=?";
        Map<String, Object> map = jt.queryForMap(sql, 1);
        System.out.println(map);
    }

  queryForList();查询所有记录封装到list集合中

@Test
    public void test02(){
        String sql = "select * from t_user";
        List<Map<String, Object>> maps = jt.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }

  query();   查询出来的单个对象封装为一个javabean

@Test
    public void test04(){
        String sql ="SELECT * FROM t_user";
        List<User> userList = jt.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rst, int i) throws SQLException {
                User u = new User();
                int id = rst.getInt(1);
                String username = rst.getString(2);
                String password = rst.getString(3);
                u.setId(id);
                u.setUsername(username);
                u.setPassword(password);
                return u;
            }
        });
        for (User user : userList) {
            System.out.println(user);
        }
    }

//使用RowMapper的实现类BeanPropertyRowMapper
//注意该方法中必须保证bean中各个属性的数据名于数据库中字段名一致。数据类型也需要注意
@Test public void test05(){ String sql ="SELECT * FROM t_user"; List<User> userList = jt.query(sql,new BeanPropertyRowMapper<User>(User.class)); for (User user : userList) { System.out.println(user); } }

  queryForObject();  用于聚合函数的执行

@Test
    public void test06(){
        String sql = "select count(id) from t_user";
        Long aLong = jt.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }

4. 不用close(),因为模板会自动处理

 
上一篇:正睿OI DAY10 ks3


下一篇:笔记53-Spring jdbcTemplate&声明式事务