package test.dao; import <a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.util.List; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import test.bean.User; import test.mapper.UserRowMapper; public class UserDao { private JdbcTemplate jdbcTemplate = null; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } // create table public void createTable() { String sql = "create table test(name varchar(50))"; this.jdbcTemplate.execute(sql); } // update insert delete public void update() { String sql = "update user set name = ? where id = ?"; String name = "张胜鸿"; int id = 100; this.jdbcTemplate.update(sql, new Object[] { name, id }); } // count(*) public void count() { String sql = "select count(1) from user"; int count = this.jdbcTemplate.queryForInt(sql); System.out.println(count); } // select String public void selectByString() { String sql = "select name from user where id = ?"; int id = 100; String name = this.jdbcTemplate.queryForObject(sql, new Object[] { id }, java.lang.String.class); System.out.println(name); } // select object public void selectByObject() { String sql = "select * from user where id = ?"; int id = 100; User user = this.jdbcTemplate.queryForObject(sql, new Object[] { id }, new UserRowMapper()); System.out.println(user.getName()); } // select list public void selectByList() { String sql = "select * from user"; List<User> list = this.jdbcTemplate.query(sql, new UserRowMapper()); for (User user : list) { System.out.println(user.getId() + ";" + user.getName()); } } // select row @SuppressWarnings("unchecked") public void selectByRows() { String sql = "select * from user"; List rows = this.jdbcTemplate.queryForList(sql); for (int i = 0; i < rows.size(); i++) { Map map = (Map) rows.get(i); System.out.println(map.get("name")); } } } mapper [java] view plain copy print? package test.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import test.bean.User; public class UserRowMapper implements RowMapper<User> { public User mapRow(ResultSet rs, int index) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); return user; } }