spring -- Spring笔记6 Jdbc
Spring笔记6 Jdbc
2016年1月29日
9:37
Spring 通过 JdbcTemplate对数据库进行操作
以下是对bean的配置:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<context:property-placeholder location=”classpath:db.propertise”/> <bean id=”dataSource” class=”com.mchange.v2.c3p0.ComboPooledDataSource”> <property name=”user” value=”${jdbc.user}”></property> <property name=”password” value=”${jdbc.password}”></property> <property name=”driverClass” value=”${jdbc.driverclass}”></property> <property name=”jdbcUrl” value=”${jdbc.jdbcurl}”></property> </bean> <!– 配置Spring的JdbcTemplate –> <bean id=”jdbcTemplate” class=”org.springframework.jdbc.core.JdbcTemplate”> <property name=”dataSource” ref=”dataSource”></property> </bean> |
Jdbc.java文件:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.firefly.spring.jdbc; import java.sql.SQLException; import javax.sql.DataSource; 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 com.firefly.spring.domain.User; public class Jdbc { private ApplicationContext ac = null; private JdbcTemplate jdbcTemplate; { ac = new ClassPathXmlApplicationContext(“jdbcContext.xml”); jdbcTemplate = (JdbcTemplate)ac.getBean(“jdbcTemplate”); } @Test public void testSelect(){ String sql = “select id,name from user where id=?”; RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); User user = jdbcTemplate.queryForObject(sql, rowMapper,1); System.out.println(user); } //以下方法用于实现对数据库的修改,即:插入,修改,删除操作 @Test public void testUpdate(){ String sql = “UPDATE user SET name=? where id=?”; jdbcTemplate.update(sql,”Tom”,1); } @Test public void testDataSource() throws SQLException { DataSource dataSource = ac.getBean(DataSource.class); System.out.println(dataSource.getConnection()); } } |
已使用 Microsoft OneNote 2016 创建。
