Spring的JdbcTemplate模板类

A.Spring提供有DAO支持模板类,功能类似于Apache 的DbUtils.
B.常用API

public int update(String sql, Object... args) 执行DML语句.增、删、改语句 

public  T query(String sql, ResultSetExtractor rse, Object... args) 执行DQL语句.查询单条/多条记录

C.基础实例
a.导入jar包

//核心包(4个) 
spring‐beans‐5.1.8.RELEASE.jar
spring‐context‐5.1.8.RELEASE.jar
spring‐core‐5.1.8.RELEASE.jar
spring‐expression‐5.1.8.RELEASE.jar
//日志包(1个) 
spring‐jcl‐5.1.8.RELEASE.jar
//jdbc包(1个) 
spring‐jdbc‐5.1.8.RELEASE.jar
//事务包(1个) 
spring‐tx‐5.1.8.RELEASE.jar
//c3p0包(2个) 
c3p0‐0.9.5.4.jar
mchange‐commons‐java‐0.2.16.jar
//mysql驱动包(1个) 
mysql‐connector‐java‐8.0.11.jar

b.增删改查

//增删改 
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); 
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); 
jdbcTemplate.update("update tb_account set username = ? where id = ?","b",1);

//查询单条记录 
Account account = jdbcTemplate.query("select * from tb_account where id = ?", new ResultSetExtractor<Account>() {
 @Override 
 public Account extractData(ResultSet resultSet) throws SQLException, DataAccessException { 
 Account existAccount = null; 
 	while (resultSet.next()) { 
 	existAccount = new Account(resultSet.getInt("id"),resultSet.getString("username"),resultSet.getDoub le("money"));
  }
  	return existAccount; 
  	}
  },1); 
  System.out.println(account);

//查询多条记录 
List<Account> accountList = jdbcTemplate.query("select * from tb_account", new ResultSetExtractor<List<Account>>() { 
@Override 
public List<Account> extractData(ResultSet resultSet) throws SQLException, DataAccessException { 
	List<Account> existAccountList = new ArrayList<>(); 
	while (resultSet.next()) { 
	Account existAccount = new 	Account(resultSet.getInt("id"),resultSet.getString("username"),resultSet.getDoub le("money"));
	existAccountList.add(existAccount); 
}
	return existAccountList;
 }
}); 
	System.out.println(accountList);

你可能感兴趣的:(笔记)