JdbcTemplate学习笔记

来源:互联网 发布:mac office2016 破解 编辑:程序博客网 时间:2024/05/13 08:51

JdbcTemplate学习笔记

快乐无极 , 2008/09/08 11:16 ,开发文档 ,评论(0) ,阅读(57567) , Via JavaEye 大 | 中 | 小
引用功能被关闭了。

JdbcTemplate学习笔记

1、使用JdbcTemplate的execute()方法执行SQL语句

Java 代码
        
  1. jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");    
  2. jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");  

2、如果是UPDATE或INSERT,可以用update()方法。

Java 代码
        
  1. jdbcTemplate.update("INSERT INTO USER VALUES('"      
  2. + user.getId() + "', '"      
  3. + user.getName() + "', '"      
  4. + user.getSex() + "', '"      
  5. + user.getAge() + "')");      
  6. jdbcTemplate.update("INSERT INTO USER VALUES('"      
  7. + user.getId() + "', '"      
  8. + user.getName() + "', '"      
  9. + user.getSex() + "', '"      
  10. + user.getAge() + "')");  

3、带参数的更新

Java代码
        
  1. jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?",new Object[] {name, id});        
  2. jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?",new Object[] {name, id});  
Java代码
        
  1. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()});        
  2. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()});  

4、使用JdbcTemplate进行查询时,使用queryForXXX()等方法

Java代码
        
  1. int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");        
  2. int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");  
Java代码
        
  1. String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?",new Object[] {id}, java.lang.String.class);        
  2. String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?",new Object[] {id}, java.lang.String.class);  
Java代码
        
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");        
  2. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");  
Java代码
        
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");      
  2. Iterator it = rows.iterator();      
  3. while(it.hasNext()) {      
  4. Map userMap = (Map) it.next();      
  5. System.out.print(userMap.get("user_id") +"\t");      
  6. System.out.print(userMap.get("name") +"\t");      
  7. System.out.print(userMap.get("sex") +"\t");      
  8. System.out.println(userMap.get("age") +"\t");      
  9. }      
  10.       
  11. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");      
  12.       
  13. Iterator it = rows.iterator();      
  14. while(it.hasNext()) {      
  15. Map userMap = (Map) it.next();      
  16. System.out.print(userMap.get("user_id") +"\t");      
  17. System.out.print(userMap.get("name") +"\t");      
  18. System.out.print(userMap.get("sex") +"\t");      
  19. System.out.println(userMap.get("age") +"\t");
        
        
  20. }  

JdbcTemplate将我们使用的JDBC的流程封装起来,包括了异常的捕捉、SQL的执行、查询结果的转换等等。spring大量使用Template Method模式来封装固定流程的动作,XXXTemplate等类别都是基于这种方式的实现。

除了大量使用Template Method来封装一些底层的操作细节,spring也大量使用callback方式类回调相关类别的方法以提供JDBC相关类别的功能,使传统的JDBC的使用者也能清楚了解spring所提供的相关封装类别方法的使用。

JDBC的PreparedStatement

Java代码
        
  1. final String id = user.getId();        
  2. final String name = user.getName();        
  3. final String sex = user.getSex() +"";        
  4. final int age = user.getAge();      
  5.       
  6. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",      
  7.       
  8. new PreparedStatementSetter() {        
  9. public void setValues(PreparedStatement ps)throws SQLException {        
  10. ps.setString(1, id);      
  11. ps.setString(2, name);      
  12. ps.setString(3, sex);      
  13. ps.setInt(4, age);      
  14. }      
  15. });      
  16.       
  17. final String id = user.getId();      
  18. final String name = user.getName();      
  19. final String sex = user.getSex() +"";      
  20. final int age = user.getAge();      
  21.         
  22. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",      
  23.         
  24. new PreparedStatementSetter() {          
  25. public void setValues(PreparedStatement ps)throws SQLException {        
  26. ps.setString(1, id);        
  27. ps.setString(2, name);          
  28. ps.setString(3, sex);        
  29. ps.setInt(4, age);          
  30. }        
  31. });        
Java代码
        
  1. final User user = new User();          
  2. jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",        
  3. new Object[] {id},        
  4. new RowCallbackHandler() {        
  5. public void processRow(ResultSet rs)throws SQLException {        
  6. user.setId(rs.getString("user_id"));      
  7. user.setName(rs.getString("name"));      
  8. user.setSex(rs.getString("sex").charAt(0));        
  9. user.setAge(rs.getInt("age"));        
  10. }      
  11. });      
  12.       
  13. final User user = new User();      
  14.         
  15. jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",        
  16. new Object[] {id},          
  17. new RowCallbackHandler() {      
  18.       
  19.       
  20. public void processRow(ResultSet rs)throws SQLException {        
  21. user.setId(rs.getString("user_id"));        
  22. user.setName(rs.getString("name"));        
  23. user.setSex(rs.getString("sex").charAt(0));        
  24. user.setAge(rs.getInt("age"));        
  25. }        
  26. });  
Java代码
        
  1. class UserRowMapper implements RowMapper {      
  2.       
  3. public Object mapRow(ResultSet rs,int index) throws SQLException {      
  4.       
  5. User user = new User();      
  6. user.setId(rs.getString("user_id"));          
  7. user.setName(rs.getString("name"));        
  8. user.setSex(rs.getString("sex").charAt(0));          
  9. user.setAge(rs.getInt("age"));          
  10. return user;            
  11. }             
  12. }      
  13.         
  14. public List findAllByRowMapperResultReader() {          
  15.       
  16. String sql = "SELECT * FROM USER";      
  17.       
  18. return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));      
  19.       
  20. }      
  21.       
  22. class UserRowMapper implements RowMapper {      
  23.       
  24. public Object mapRow(ResultSet rs, int index) throws SQLException {      
  25. User user = new User();        
  26. user.setId(rs.getString("user_id"));        
  27. user.setName(rs.getString("name"));        
  28. user.setSex(rs.getString("sex").charAt(0));        
  29. user.setAge(rs.getInt("age"));        
  30. return user;        
  31. }        
  32. }      
  33.       
  34. public List findAllByRowMapperResultReader() {          
  35. String sql = "SELECT * FROM USER";        
  36. return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));      
  37. }  

在getUser(id)里面使用UserRowMapper

Java代码
        
  1. public User getUser(final String id)throws DataAccessException {        
  2. String sql = "SELECT * FROM USER WHERE user_id=?";        
  3. final Object[] params = new Object[] { id };        
  4. List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));          
  5. return (User) list.get(0);        
  6. }    
  7.       
  8. public User getUser(final String id)throws DataAccessException {      
  9. String sql = "SELECT * FROM USER WHERE user_id=?";          
  10. final Object[] params = new Object[] { id };          
  11. List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));          
  12. return (User) list.get(0);          
  13. }

网上收集

org.springframework.jdbc.core.PreparedStatementCreator 返回预编译SQL 不能于Object[]一起用

Java代码
        
  1. public PreparedStatement createPreparedStatement(Connection con)throws SQLException {        
  2. return con.prepareStatement(sql);        
  3. }      
  4.       
  5. public PreparedStatement createPreparedStatement(Connection con)throws SQLException {        
  6. return con.prepareStatement(sql);        
  7. }  

1.增删改

org.springframework.jdbc.core.JdbcTemplate 类(必须指定数据源dataSource)

Java代码
        
  1. template.update("insert into web_person values(?,?,?)",Object[]);        
  2. template.update("insert into web_person values(?,?,?)",Object[]);  
        

Java代码
        
  1. template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){//匿名内部类 只能访问外部最终局部变量        
  2. public void setValues(PreparedStatement ps)throws SQLException {        
  3. ps.setInt(index++,3);        
  4. });      
  5.       
  6. template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){//匿名内部类 只能访问外部最终局部变量      
  7.       
  8. public void setValues(PreparedStatement ps)throws SQLException {        
  9. ps.setInt(index++,3);        
  10. });      
  11.       
  12. org.springframework.jdbc.core.PreparedStatementSetter //接口 处理预编译SQL            
  13. public void setValues(PreparedStatement ps)throws SQLException {        
  14. ps.setInt(index++,3);        
  15. }      
  16.       
  17. public void setValues(PreparedStatement ps)throws SQLException {        
  18. ps.setInt(index++,3);        
  19. }  

2.查询JdbcTemplate.query(String,[Object[]/PreparedStatementSetter],RowMapper/RowCallbackHandler)

org.springframework.jdbc.core.RowMapper 记录映射接口 处理结果集

Java代码
        
  1. public Object mapRow(ResultSet rs,int arg1) throws SQLException {//int表当前行数        
  2. person.setId(rs.getInt("id"));        
  3. }        
  4. List template.query("select * from web_person where id=?",Object[],RowMapper);        
  5. public Object mapRow(ResultSet rs,int arg1) throws SQLException {//int表当前行数        
  6. person.setId(rs.getInt("id"));        
  7. }        
  8. List template.query("select * from web_person where id=?",Object[],RowMapper);  

org.springframework.jdbc.core.RowCallbackHandler 记录回调管理器接口 处理结果集

Java代码
        
  1. template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){        
  2. public void processRow(ResultSet rs)throws SQLException {        
  3. person.setId(rs.getInt("id"));        
  4. });