一、搭建环境
1.引入JAR包。数据库驱动,spring的基础包,spring的jdbc包
2.新建XML文件
二、使用JDBC模版
1.使用DBCP
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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"
>
<!-- 增加DriverManagerDataSouerce -->
<!-- DBCP -->
<bean id="dataSouerce" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="Url" value="jdbc:mysql:///spring4_day03"/>
<property name="username" value="root"/>
<property name="password" value="a"/>
</bean>
<!-- C3P0-->
<!-- <bean id="dataSouerce" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///spring4_day03"/>
<property name="user" value="root"/>
<property name="password" value="a"/>
</bean>
-->
<!-- 增加JDBCTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSouerce"></property>
</bean>
</beans>
三、使用属性文件配置
1.创建属性文件jdbc.properties
2.写入
DriverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///数据库名
username=root
password=密码
3.XML中引入context标签。还有beans标签的配置
<context:property-placeholder location="classpath:jdbc.properties"/>
四、JDBC模版增删改查的使用
//query
@Test
public void test4() {
long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println("query count = " + count);
}
//query a record to object
@Test
public void test5() {
try {
Account account = (Account) jdbcTemplate.queryForObject("select id,name,money from account where id = ?", new MyRowMap(),20);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
//query more records to list
@Test
public void test6() {
List<Account> list = jdbcTemplate.query("select * from account", new MyRowMap());
for (Account account : list) {
System.out.println(account);
}
}
//必须写一个内部类,继承RowMapper接口
class MyRowMap implements RowMapper{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
return account;
}
}