不同持久化技术对应的模板类:
JDK5.0以上版本可以使用jdbc.core.simple.SimpleJdbcTemplate的模板类。
数据源
Spring在第三方依赖包中包含两个数据源的实现包类,一是Apache的DBCP,二是C3P0
使用实例:
// DBCP
<context:property-placeholder location="classpath:chapter9/jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
// C3P0
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
p:user="${user}" p:password="${password}" p:driverClass="${driverClass}"
p:jdbcUrl="${jdbcUrl}">
</bean>
利用数据源创建、删除数据库表
例:
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class UseJdbcTemplate {
private static JdbcTemplate jdbcTemplate;
@BeforeClass
public static void setUpClass(){
String url = "jdbc:mysql://localhost:3306/db_transaction";
String username = "root";
String password = "hehe";
DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username, password);
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
jdbcTemplate = new JdbcTemplate(dataSource);
}
// 创建
@Test
public void setUp() {
String createTableSql = "CREATE TABLE t_forum (" + "forumId INT,forumName CHAR(20),forumDesc CHAR(20)" + ");";
jdbcTemplate.update(createTableSql);
createTableSql="CREATE TABLE t_post (" + "postId int, topicId int, forumId int, userId int, " +
"postText CHAR(20), postAttach char(4), postTime date" + ");";
jdbcTemplate.update(createTableSql);
}
// 删除
@Test
public void tearDown() {
String dropTableSql = "drop table t_forum,t_post,t_topic ";
jdbcTemplate.execute(dropTableSql);
}
}