Config.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.password=
测试数据库更新操作
@Test//Spring配置的jdbctemplate
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("Config.xml");
JdbcTemplate jdbcTemplate= (JdbcTemplate) context.getBean("jdbcTemplate");
//其返回值是受影响的行数
System.out.println(jdbcTemplate.update("delete from account where name='李明'"));
jdbcTemplate.update("insert into account values (?,?)","张飞",9000);
jdbcTemplate.update("update account set money=900 where name='张飞'");
}
查询用另一种测试方法Junit
查询列表
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:Config.xml")
public class junitText {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testQuery(){
List<Account> list = jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
Iterator it = list.iterator();
while (it.hasNext())
System.out.println(it.next());
}
}
结果
查询单个结果
@Test
public void testQueryOne(){
Account tom= jdbcTemplate.queryForObject("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),"关羽");
System.out.println(tom);
}
查询基本数据类型
@Test
public void testQueryCount(){
System.out.println("总共有"+jdbcTemplate.queryForObject("select count(*) from account",Integer.class)+"条数据");
}
关键点有:
jdbctemplate.setDatasource() //可交给spring容器
以及:
jdbctemplate.query() //查列表
jdbctemplate.queryForObject() //查单个
jdbctemplate.update(); //增删改,返回值为操作行数。