1.导入jar包(c3p0)
2.在spring配置文件中配置数据源和JdbcTemplate的bean
<?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">
<!-- 配置数据源(里面存放了若干个连接对象):数据库交互的。 数据源:c3p0,druid(阿里) --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="root"/> <property name="password" value="123"/> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"></property> </bean>
<!-- 配置springJdbc的模板类 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> </beans> |
3.在单元测试测试
package com.zhiyou100.kfs.test;
import java.util.ArrayList; import java.util.List;
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper;
import com.zhiyou100.kfs.bean.User;
class TestJdbcTemplate {
private static JdbcTemplate jdbcTemplate; @BeforeAll static void setUpBeforeClass() throws Exception { jdbcTemplate =(JdbcTemplate)new ClassPathXmlApplicationContext("applicationContext.xml").getBean("jdbcTemplate"); }
@AfterAll static void tearDownAfterClass() throws Exception { }
/** * 增删改 */ @Test void testUpdate() { String sql="insert into tb_user (uusername) value('张八');"; jdbcTemplate.update(sql); } /** * 多条添加 */ @Test void testBatchUpdate() { String sql1="insert into tb_user (uusername) value(?);"; String sql2="insert into tb_user (uusername) value('张十');"; List<Object[]> list=new ArrayList<>(); String[] uusername1=new String[] {new String("张九2")}; String[] uusername2=new String[] {new String("张九3")}; jdbcTemplate.batchUpdate(sql1, list); } /** * 查询一条记录 */ @Test void testQueryOne() { String sql="select * from tb_user where u_id=?;"; RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class); User user=jdbcTemplate.queryForObject(sql, rowMapper,1); System.out.println(user); } /** * 查询多条记录 */ @Test void testQueryList() { String sql="select * from tb_user;"; RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class); List<User> list=jdbcTemplate.query(sql, rowMapper); System.out.println(list); } /** * 查询单值(有多少条记录) */ @Test void testQuerySingtonColumn() { String sql="select count(u_id) c from tb_user;"; int a=jdbcTemplate.queryForObject(sql, Integer.class); System.out.println(a); } } |