需要额外导入的Jar包: spring-jdbc-4.2.4.RELEASE.jar----spring-tx-4.2.4.RELEASE.jar----spring-aop-4.2.4.RELEASE.jar----spring-test-4.2.4.RELEASE.jar----com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar----mysql-connector-java-5.1.7-bin.jar
参考DBUtil的QueryRunner:update() 增、删、改操作 ; query() 查询操作
Test.java(测试类):
package cn.xxx.jdbctemplate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test {
@Test
public void fun1() throws Exception{
//一、准备连接池(c3p0)
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///数据库名");
dataSource.setUser("root");
dataSource.setPassword("1234");
//二、创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate(); //类似DBUtil中的QueryRunner
//JdbcTemplate jt = new JdbcTemplate(dataSource); //也可以通过构造函数,直接设置DataSource
jt.setDataSource(dataSource);
//三、书写sql,并执行
String sql = "insert into t_user values(null,'rose') ";
jt.update(sql); // update执行 增、删、改的操作
}
}