时间:2021-07-01 10:21:17 帮助过:19人阅读
增,删,改的代码、
public class UserDaoImpl { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void add() { User user = new User(); user.setUsername("关羽"); user.setPassword("456"); user.setAge(43); user.setAddress("荆州"); String sql = "insert into t_user (username,password,age,address) values (?,?,?,?)"; jdbcTemplate.update(sql, user.getUsername(), user.getPassword(),user.getAge(), user.getAddress()); } public void delete() { String username = "张飞"; String sql = "delete from t_user where username=?"; jdbcTemplate.update(sql, username); } public void update() { String sql = "update t_user set age=?, address=? where username=?"; jdbcTemplate.update(sql, "45", "蜀国", "关羽"); }
查询功能:
<1.返回单一对象
//返回单一对象 public void find1() { String sql = "select * from t_user where username=?"; User user = jdbcTemplate.queryForObject(sql, new MapRow(), "关羽"); System.out.println(user); }
new MapRow()的对象
class MapRow implements RowMapper<User> { @Override public User mapRow(ResultSet arg0, int arg1) throws SQLException { // TODO Auto-generated method stub String username = arg0.getString("username"); String password = arg0.getString("password"); Integer age = arg0.getInt("age"); String address = arg0.getString("address"); User user = new User(); user.setUsername(username); user.setPassword(password); user.setAge(age); user.setAddress(address); return user; } }
<2.返回List集合
//返回List集合 public void find2(){ String sql = "select * from t_user"; List<User> list = jdbcTemplate.query(sql, new MapRow()); for (User user : list) { System.out.println(user); } }
测试类:
@Test public void DemoTest() { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); UserDaoImpl userDaoImpl = (UserDaoImpl) ctx.getBean("userDaoImpl"); // userDaoImpl.add(); // userDaoImpl.delete(); // userDaoImpl.update(); // userDaoImpl.find1(); userDaoImpl.find2(); }
对增,删,改,的批量操作时,用到方法batchUpdate(sql, batchArgs);
batchArgs为Object类的数组
spring中的jdbcTemplate
标签:source method find drive 批量 classname classpath insert update