- maven引入Spring JDBC
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.19</version></dependency>
- Spring配置中配置
<!-- DataSource配置 --><bean id="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close" p:driverClass="${jdbc.driverClassName}"p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}"p:password="${jdbc.password}" /><!-- jdbcTemplate配置 --> <bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean>
- 测试
package testSpring;import java.util.ArrayList; import java.util.List;import org.junit.Test; import org.springframework.context.ApplicationContext; 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 test.spring.model.User;public class TestSpring {@Testpublic void testUser() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");JdbcTemplate jdbcTemplate= ac.getBean(JdbcTemplate.class);/* 增加 */String sql1="insert into 'users' ('userName','password') values (?,?) ";jdbcTemplate.update(sql1, "abc","abc123");/* 删除 */String sql2="delete from 'users' where id=? ";jdbcTemplate.update(sql2, 1);/* 查找一个对象 */String sql3 = "select * from User where id=?";RowMapper< User> mapper=new BeanPropertyRowMapper<>(User.class);User user=jdbcTemplate.queryForObject(sql3, mapper, 1);System.out.println(user);/* 查找出多个数据 */String sql4 = "select * from User where id>?";RowMapper< User> mapper2=new BeanPropertyRowMapper<>(User.class);List<User> users =jdbcTemplate.query(sql4, mapper2, 0);System.out.println(users);/* 查找显示单个列值 */String sql5 = "select count(id) from users";Long count=jdbcTemplate.queryForObject(sql5, Long.class);System.out.println(count);/*批量插入*/String sql7="insert into 'users' ('userName','password') values (?,?) ";List<Object[]> args=new ArrayList<>();args.add(new Object[] {"aa","aa123"});args.add(new Object[] {"bb","bb123"});jdbcTemplate.batchUpdate(sql7, args);}}