项目的运行环境基于这篇文章十六、Spring通过IOC管理JDBC模板
jdbc模板的增删改都可以使用同一个方法,即update方法。
查询方法这里介绍2种,一个是单条记录查询,另一个是多条记录查询,前者使用queryForObject方法,后者使用query方法,但无论使用哪种查询方法,它们都有很多重载的方法,我这里使用的是传入参数有RowMapper接口的。
RowMapper接口需要我们去实现它的mapRow方法,在该方法中完成每一条记录的封装,注意:没查询一条记录就会回调一次该方法。
好了,下面直接上代码
package blog.csdn.net.mchenys.test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* jdbc模板的增删改查
*
* @author mChenys
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo2 {
@Resource(name = "jdbcTemplate")
private JdbcTemplate jdbcTemplate;
// 添加
@Test
public void testAdd() {
jdbcTemplate.update("insert into t_account values(null,?,?)", "张三", 100);
}
// 修改
@Test
public void testUpdate() {
jdbcTemplate.update("update t_account set money=? where name=?", 200, "张三");
}
// 删除
@Test
public void testDelete() {
jdbcTemplate.update("delete from t_account where name=?", "张三");
}
// 单个查询
@Test
public void queryOne() {
Account account = jdbcTemplate.queryForObject("select * from t_account where id=?", new BeanMapper(), 1);
System.out.println(account);
}
// 所有查询
@Test
public void queryAll() {
List<Account> list = jdbcTemplate.query("select * from t_account", new BeanMapper());
for (Account account : list) {
System.out.println(account);
}
}
// 手动的来封装数据(一行一行封装数据)
class BeanMapper implements RowMapper<Account> {
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account ac = new Account();
ac.setId(rs.getInt("id"));
ac.setName(rs.getString("name"));
ac.setMoney(rs.getDouble("money"));
return ac;
}
}
//java bean
class Account {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
}