eg.类似于添加:
String sql = "update t_book set user_id=?,username=? where ustatus=?"; Object[] args = {book.getUsedId(), book.getUserName(), book.getUstatus()}; int update = jdbcTemplate.update(sql, args); System.out.println(update);
eg.类似于添加,基于id删除
public void delete(String id) { String sql = "delete from t_book where user_id=?"; int update = jdbcTemplate.update(sql, id); System.out.println(update); }
eg. 查询表中有多少记录,返回某个值
sql语言: SELECT COUNT(*) FROM t_book
将返回一个数字表示记录数
利用JdbcTemplate实现查询返回某个值代码(queryForObject)
jdbcTemplate.queryForObject(String sql, Class<T> requiredType)
eg
public int selectCount() { String sql = "select count(*) from t_book"; Integer count = jdbcTemplate.queryForObject(sql, Integer.class); return count; }
eg. 场景:查询图书的详情页面(一种对象)
利用JdbcTemplate实现查询返回对象(queryForObject)
jdbcTemplate.queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
eg.
public Book findBookInfo(String id) { String sql = "select * from t_book where user_id=?"; //调用方法实现 Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id); return book; }
eg. 场景:查询图书列表分页(集合)
利用JdbcTemplate实现查询返回对象(queryForObject)
jdbcTemplate.queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
eg.
public List<Book> findAllBook() { String sql = "selet * from t_book"; List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class)); return list; }