jdbctemplate的小练习

在junit环境下测试



import mystring.demo4.Teacher;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

//使用JdbcTemplate完成一些练习
public class JDBCdemo11 {
    private JdbcTemplate jdbcTemplate;

    @Before
    public void init(){
        //获取jt的对象
        jdbcTemplate = new JdbcTemplate(JDBCUntils1.getDataSource());
    }

    @Test
    public void test1(){
        //将郭奉孝的余额修改为2000
        String sql = "update account set money = ? where name = ‘郭奉孝‘";
        int update = jdbcTemplate.update(sql, 2000);    //影响的行数
        System.out.println(update);
    }

    @Test
    public void test2(){
        //添加一条记录
        String sql = "insert into account values(?,?)";
        int i = jdbcTemplate.update(sql, "孙策", 1400);
        System.out.println(i);
    }

    @Test
    public void test3(){
        //删除刚才添加的东西
        String sql = "delete from account where name = ?";
        int i = jdbcTemplate.update(sql, "孙策");
        System.out.println(i);
    }

    @Test
    public void test4(){
        //查询姓名为郭奉孝的人,并装载进map
        String sql = "select * from account where name = ?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, "郭奉孝");
        System.out.println(map);
    }

    @Test
    public void test5(){
        //查询所有记录装载进list
        String sql = "select * from account";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }

    @Test
    public void test6(){
        //查询所有记录封装为Teacher类并装入list集合
        String sql = "select * from account";
        List<Teacher> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Teacher>(Teacher.class));
        for (Teacher teacher : list) {
            System.out.println(teacher);
        }
    }

    @Test
    public void test7(){
        //查询记录总数
        String sql = "select count(name) from account";
        Long aLong = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }
}


jdbctemplate的小练习

上一篇:Spring事务异常回滚,捕获异常不抛出就不会回滚


下一篇:Java Excel导出多个工作表(添加多个sheet)