C/C++教程

jdbctemplate的小练习

本文主要是介绍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的小练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!