1.进行增删改的操作
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "INSERT INTO product VALUES (NULL, ?, ?);";
jdbcTemplate.update(sql, "iPhone3GS", 3333);
2.进行查询的操作
2.1 返回一个int整数
String sql = "SELECT pid FROM product WHERE price=18888;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
int forInt = jdbcTemplate.queryForInt(sql);
2.2 返回一个Map集合
String sql = "SELECT * FROM product WHERE pid=?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 6);
2.3 返回一个List集合
String sql = "SELECT * FROM product WHERE pid<?;";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 8);
2.4 RowMapper返回自定义对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "SELECT * FROM product;";
List<Product> query = jdbcTemplate.query(sql, new RowMapper<Product>() {
@Override
public Product mapRow(ResultSet arg0, int arg1) throws SQLException {
Product p = new Product();
p.setPid(arg0.getInt("pid"));
p.setPname(arg0.getString("pname"));
p.setPrice(arg0.getDouble("price"));
return p;
}
});
2.5 BeanPropertyRowMapper返回自定义对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的SQL语句
String sql = "SELECT * FROM product;";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));