1、表的操作
使用JdbcTemplate的execute()方法执行SQL语句
execute方法总是使用 java.sql.Statement,不接受参数,而且他不返回受影响记录的计数,更适合于创建和丢弃表的语句。
代码
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");
2、增、删和改
update方法update方法返回的是受影响的记录数目的一个计数,并且如果传入参数的话,使用的是java.sql.PreparedStatement,更适合于插入,更新和删除操作
1)不带参数的更新
代码
jdbcTemplate.update("INSERT INTO USER VALUES('"
+ user.getId() + "', '"
+ user.getName() + "', '"
+ user.getSex() + "', '"
+ user.getAge() + "')");
2)带参数的更新
代码:jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id});
代码:jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.g etId(), user.getName(), user.getSex(), user.getAge()});
3)JDBC的PreparedStatement
代码:------单个更新
final String id = user.getId();
final String name = user.getName();
final String sex = user.getSex() + "";
final int age = user.getAge();
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, id); //需要注意: 匿名内部类 只能访问外部最终局部变量
ps.setString(2, name);
ps.setString(3, sex);
ps.setInt(4, age);
}
});
代码:------批量更新
需要批处理,可以实现org.springframework.jdbc.core.BatchPrepared- StatementSetter接口:
package org.springframework.jdbc.core;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public interface BatchPreparedStatementSetter {
void setValues(PreparedStatement ps,
int i) throws SQLException;
int getBatchSize();
}
...
public int[] insertUsers(final List users) {
String sql = "INSERT INTO user (name,age) VALUES(?,?)";
BatchPreparedStatementSetter setter =
new BatchPreparedStatementSetter() {
public void setValues(
PreparedStatement ps, int i) throws SQLException {
User user = (User) users.get(i);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge().intValue());
}
public int getBatchSize() {
return users.size();
}
};
return jdbcTemplate.batchUpdate(sql, setter);
}
...
如果JDBC驱动程序支持批处理,则直接使用它的功能,如果不支持, Spring则会一个一个自动处理更新以模拟批处理。
3、查询
1)使用JdbcTemplate进行查询时,使用queryForXXX()等方法
• Queries, using convenience methods
代码:int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");
代码:String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?", new Object[] {id}, java.lang.String.class);
代码:List rows = jdbcTemplate.queryForList("SELECT * FROM USER");
Returns an ArrayList (one entry for each row) of HashMaps (one entry for each column using the column name as the key)
代码:
List rows = jdbcTemplate.queryForList("SELECT * FROM USER");
Iterator it = rows.iterator();
while(it.hasNext()) {
Map userMap = (Map) it.next();
System.out.print(userMap.get("user_id") + "\t");
System.out.print(userMap.get("name") + "\t");
System.out.print(userMap.get("sex") + "\t");
System.out.println(userMap.get("age") + "\t");
}
2)JDBC的callback方式
• Queries, using callback method
A)processRow
在查询到数据之后先作一些处理再传回。可以实现org.springframework.jdbc.core.RowCallbackHandler接口
代码:------单行查询
final User user = new User();
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",
new Object[] {id},
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException { //需要注意: 匿名内部类 只能访问外部最终局部变量
user.setId(rs.getString("user_id"));
user.setName(rs.getString("name"));
user.setSex(rs.getString("sex").charAt(0));
user.setAge(rs.getInt("age"));
}
});
代码:------多行查询
final List employees = new LinkedList();
jdbc.query("select EMPNO, FIRSTNME, LASTNAME from EMPLOYEE",
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Employee e = new Employee();
e.setEmpNo(rs.getString(1));
e.setFirstName(rs.getString(2));
e.setLastName(rs.getString(3));
employees.add(e);
}
}
);
employees list will be populated with Employee objects
B) RowMapper
一次要取回很多查询结果的对象,则可以先实现org.springframe- work.jdbc.core.RowMapper接口。
代码:------将数据表中的数据影射成其对应的JAVA类的对象,mapRow回调方法会被ResultSet中的每一行调用。
class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int index) throws SQLException {
User user = new User();
user.setId(rs.getString("user_id"));
user.setName(rs.getString("name"));
user.setSex(rs.getString("sex").charAt(0));
user.setAge(rs.getInt("age"));
return user;
}
}
传回的结果已使用UserRowMapper的定义,将之封装为User对象。
//返回多行查询结果
public List findAllByRowMapperResultReader() {
String sql = "SELECT * FROM USER";
return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));
}
the return list will be populated with User objects
//返回单行查询结果
在getUser(id)里面使用UserRowMapper
代码
public User getUser(final String id) throws DataAccessException {
String sql = "SELECT * FROM USER WHERE user_id=?";
final Object[] params = new Object[] { id };
List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));
return (User) list.get(0);
}