JdbcTemplate使用

package JdbcTemplate;

import com.itcat.domain.Emp;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import util.JdbcUtilsDruid;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Jdbctemplatedemo2 {
    private JdbcTemplate template = new JdbcTemplate(JdbcUtilsDruid.getDataSource());
    //修改数据
    @Test
    public void test1(){
        String sql = "update stu set age = 66 where id = 6";
        int count = template.update(sql);
        System.out.println(count);
    }

    //添加数据
    @Test
    public void test2(){
        String sql = "insert into stu values(?,?,?,?,?,?)";
        int count = template.update(sql, 7, "嘿嘿啊啊", 44, 22.2, Date.valueOf("2018-02-02"), Date.valueOf("2018-02-02"));
        System.out.println(count);
    }

    //查询
    @Test
    public void test3(){
        String sql = "select * from stu where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 6);
        System.out.println(map);
    }

    //查询
    @Test
    public void test4(){
        String sql = "select * from stu";
        List<Map<String, Object>> maps = template.queryForList(sql);
        System.out.println(maps);
    }

    @Test
    public void test5(){
        String sql = "select * from stu";
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet resultSet, int i) throws SQLException {
                Emp emp = new Emp();
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                double score = resultSet.getDouble("score");
                Date birthday = resultSet.getDate("birthday");
                Date insert_time = resultSet.getDate("insert_time");
                emp.setId(id);
                emp.setName(name);
                emp.setAge(age);
                emp.setScore(score);
                emp.setBirthday(birthday);
                emp.setInsert_time(insert_time);
                return emp;
            }
        });
        for (Emp emp : list) {
            System.out.println(emp);
        }

    }

    @Test
    public void test6(){
        String sql = "select * from stu";
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    @Test
    public void test7(){
        String sql = "select count(id) from stu";
        Long total = template.queryForObject(sql, Long.class);
        System.out.println(total);
    }
}

 

posted @ 2019-03-06 20:31  Erick-LONG  阅读(1200)  评论(0编辑  收藏  举报