spring中提供了一個能夠操做數據庫的對象,對象封裝了jdbc技術。這個對象的名字就叫JDBCTemplate
,JDBC模板對象。這個對象和DBUtils中的QueryRunner對象很是類似。java
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd "> <!--1將鏈接池交給spring容器管理 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///springmvc?characterEncoding=utf-8"></property> <property name="user" value="root"></property> <property name="password" value="123"></property> </bean> <!--2將JDBCTemplate放入spring容器 --> <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!--3將UserDao放入spring容器 --> <bean name="userDao" class="com.fei.a_jdbctemplate.UserDaoImpl"> <property name="jt" ref="jdbcTemplate"></property> </bean> </beans>
// 1建立容器對象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // 2向容器要對象 UserDao userDao = (UserDao) ac.getBean("userDao");
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///springmvc?characterEncoding=utf-8 jdbc.user=root jdbc.password=123
<!-- 告訴spring讓他去讀取db.properties配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!--1將鏈接池交給spring容器管理 --> <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean>