通过对 JdbcTemplate源代码的研读,可以看到,在 JdbcTemplate提供了很多用来查询的数
据库,比如:queryForMap()、queryForLong()、queryForInt()、queryForList()等等。
这里只是简单的进行示例说明,使用 queryForList查询的示例代码如下:
List rows = jdbcTemplate.queryForList("select * from hello");
Iterator it = rows.iterator();
while(it.hasNext()) {
Map map = (Map) it.next();
String id = map.get("id");
String name = map.get("name");
String msg = map.get("msg");
}
使用 queryForInt查询获得 hello表中记录数量的示例代码如下:
int count = jdbcTemplate.queryForInt("select count(*) from hello");
这里只简单介绍这 2 个查询的使用方法,如果想获得更多的查询功能,研读 JdbcTemplate
的源代码是很有用的。
JdbcTemplate更改数据库
使用 JdbcTemplate的 update()方法是进行数据库更改常用的方式。比如要往数据库插入一
笔数据,则可以使用以下示例代码:
jdbcTemplate.update("inset into hello values('1, ‘gf',’HelloWorld ')");
可以使用下面的这种示例代码来实现同样的功能:
jdbcTemplate.update("inset into hello values (?, ?, ?,)",
new Object[] {1,’gf’, ‘HelloWorld’});
还可以使用下面的这种示例代码来实现同样的功能:
jdbcTemplate.update("inset into hello values (?, ?, ?,)",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, 1);
ps.setString(2, ’gf’);
ps.setString(3, ’Hel oWorld’);
}
});
对数据库的修改,同样可以使用上面的方法:
jdbcTemplate.update("update hello set name = ‘gd’, msg = ‘HelloWorld’ where id = 1");
可以使用下面的这种示例代码来实现同样的功能:
jdbcTemplate.update("update hello set name = ?, msg = ? where id = ?",
new Object[] {’gf’, ‘HelloWorld’,1});
注意:新增和修改时 Object[]中参数的先后顺序是不一样的。