bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
测试类:
/**
* 定义Account的封装策略
*/
class AccountRowMapper implements RowMapper<Account>{
/**
* 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
* @param resultSet
* @param i
* @return
* @throws SQLException
*/
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account=new Account();
account.setId(resultSet.getInt("id"));
account.setUid(resultSet.getInt("uid"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
public class jdbcTemplateDemo {
@Test
public void testJdbcTemplateDemo(){
//获取容器
ApplicationContext factory=new ClassPathXmlApplicationContext("bean.xml");
//获取对象
JdbcTemplate jt=factory.getBean("jdbcTemplate",JdbcTemplate.class);
//执行操作
//保存
//jt.update("insert into account(uid,money) values(?,?)",44,60);
//更新
//jt.update("update account set uid=?,money=? where id=?",43,99,1);
//删除
//jt.update("delete from account where id=?",1);
//查询所有
//List<Account> accounts=jt.query("select * from account where money>?",new AccountRowMapper(),50f);
//用spring提供的方法
// List<Account> accounts=jt.query("select * from account where money>?",new BeanPropertyRowMapper<Account>(Account.class),50f);
//System.out.println(accounts);
//查询一个
//List<Account> account=jt.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),2);
//System.out.println(account.isEmpty()?"没有内容":account.get(0));
//返回一行一列(使用聚合函数,但不加group by子句)
Long count=jt.queryForObject("select count(1) from account where money>?",Long.class,50f);
System.out.println(count);
}