日期:2014-05-16 浏览次数:20397 次
Connection conn =null; Statement stmt = null; try { conn = dataSource.getConnection(); stmt = con.createStatement(); stmt.executeUpdate("UPDATE user SET age = 18 WHERE id = 'erica'"); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { logger.warn("Exception in closing JDBC Statement", ex); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { logger.warn("Exception in closing JDBC Connection", ex); } } }
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate .update( "UPDATE user SET age = ? WHERE id = ?", new PreparedStatementSetter() { public void setValues(PreparedStatementSetter ps) throws SQLException { ps.setInt(1, 18); ps.setString(2, "erica"); } } );
final List userList = new ArrayList(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate .query( "SELECT name, sex, address FROM user WHERE age > 18", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { User user = new User(); user.setId(rs.getString("name")); user.setSex(rs.getString("sex")); user.setAddress(rs.getString("address")); userList.add(product); } });这里传入query方法的有两个参数,第一个是Select查询语句,第二个是一个RowCallbackHandler实例,我们通过RowCallbackHandler对Select语句得到的每行记录进行解析,并为其创建一个User数据对象。实现了手动的OR映射。