JdbcTemplate使用
Posted Erick - LONG
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); } }
以上是关于JdbcTemplate使用的主要内容,如果未能解决你的问题,请参考以下文章
Spring对JDBC的模板支持——JdbcTemplate
使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 上篇