1、使用JdbcTemplate的execute()方法執(zhí)行SQL語句
2、如果是UPDATE或INSERT,可以用update()方法。
3、帶參數(shù)的更新
4、使用JdbcTemplate進行查詢時,使用queryForXXX()等方法
JdbcTemplate將我們使用的JDBC的流程封裝起來,包括了異常的捕捉、SQL的執(zhí)行、查詢結(jié)果的轉(zhuǎn)換等等。spring大量使用Template Method模式來封裝固定流程的動作,XXXTemplate等類別都是基于這種方式的實現(xiàn)。
除了大量使用Template Method來封裝一些底層的操作細節(jié),spring也大量使用callback方式類回調(diào)相關(guān)類別的方法以提供JDBC相關(guān)類別的功能,使傳統(tǒng)的JDBC的使用者也能清楚了解spring所提供的相關(guān)封裝類別方法的使用。
JDBC的PreparedStatement
在getUser(id)里面使用UserRowMapper
網(wǎng)上收集
org.springframework.jdbc.core.PreparedStatementCreator 返回預編譯SQL 不能于Object[]一起用
1.增刪改
org.springframework.jdbc.core.JdbcTemplate 類(必須指定數(shù)據(jù)源dataSource)
template.update("insert into web_person values(?,?,?)",Object[]);
template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ 匿名內(nèi)部類 只能訪問外部最終局部變量
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(index++,3);
});
org.springframework.jdbc.core.PreparedStatementSetter 接口 處理預編譯SQL
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(index++,3);
}
2.查詢JdbcTemplate.query(String,[Object[]/PreparedStatementSetter],RowMapper/RowCallbackHandler)
org.springframework.jdbc.core.RowMapper 記錄映射接口 處理結(jié)果集
public Object mapRow(ResultSet rs, int arg1) throws SQLException { int表當前行數(shù)
person.setId(rs.getInt("id"));
}
List template.query("select * from web_person where id=?",Object[],RowMapper);
org.springframework.jdbc.core.RowCallbackHandler 記錄回調(diào)管理器接口 處理結(jié)果集
template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
person.setId(rs.getInt("id"));
});