jt.update("insert into account(name,money) values(?,?)","ggg",333);
更新
1
jt.update("update account set name=?, money=? where id=?","test",456,8);
删除
1
jt.update("delete from account where id=?",8);
查询所有
1 2 3 4 5 6 7 8 9 10 11 12 13 14
List<Account> accounts=jt.query("select * from account where money > ?", new AccountRowMapper(), 1000f); //定义Account的封装策略 classAccountRowMapperimplementsRowMapper<Account>{ //把结果集中的数据封装到Account中,然后由Spring把每个Account加到集合中 public Account mapRow(ResultSet resultSet, int i)throws SQLException { Account account=new Account(); account.setId(resultSet.getInt("id")); account.setName(resultSet.getString("name")); account.setMoney(resultSet.getFloat("money")); return account; } } //直接使用spring提供的封装类 List<Account> accounts=jt.query("select * from account where money > ?", new BeanPropertyRowMapper<Account>(Account.class), 1000f);
查询一个
1 2
List<Account> accounts=jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1); System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
返回一行一列
1 2
//返回一行一列 int count = jt.queryForObject("select count(*) from account where money > ?",Integer.class,1000f);
publicclassAccountDaoImplimplementsIAccountDao{ private JdbcTemplate jdbcTemplate; publicvoidsetJdbcTemplate(JdbcTemplate jdbcTemplate){ this.jdbcTemplate = jdbcTemplate; } public Account findAccountById(Integer id){ List<Account> accounts=jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id); return accounts.isEmpty()?null:accounts.get(0); } public Account findAccountByName(String name){ //与唯一属性id的查询不同 List<Account> accounts=jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name); if (accounts.isEmpty()) returnnull; if (accounts.size()>1) thrownew RuntimeException("结果集不唯一"); return accounts.get(0); } publicvoidupdateAccount(Account account){ jdbcTemplate.update("update account set name=?, money=? where id=?",account.getName(),account.getMoney(),account.getId()); } }
//JdbcDaoSupport中已经包含了jdbcTemplate和dataSource的操作 publicclassAccountDaoImplextendsJdbcDaoSupportimplementsIAccountDao{ public Account findAccountById(Integer id){ List<Account> accounts=getJdbcTemplate().query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), id); return accounts.isEmpty()?null:accounts.get(0); } //... }