1.导包
com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar com.springsource.org.apache.commons.pool-1.5.3.jar mysql-connector-java-5.1.26-bin.jar
2.配置BasicDataSource对象(在spring的核心配置文件中设置)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <!-- 引入jdbc.properties --> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> </bean> </beans>
3.配置jdbc配置文件(jdbc.properties文件)
jdbc.username=数据库账号 jdbc.password=数据库密码 jdbc.url=jdbc:mysql:///数据库名 jdbc.driverClassName=com.mysql.jdbc.Driver
4.测试
@RunWith(SpringJUnit4ClassRunner.class) //加载spring核心xml文件 //@ContextConfiguration("classpath:applicationContext.xml") @ContextConfiguration public class TestMain { //Autowired将对象地址自动注入到变量dataSource里
@Autowired private DataSource dataSource; @Test public void test() throws SQLException{ Connection connection = dataSource.getConnection(); PreparedStatement ps = connection.prepareStatement("insert into 表名(字段1,字段2) values(?,?)"); ps.setObject(1, "澳大利亚"); ps.setObject(2,7); ps.executeUpdate(); } }
1.1.1. 配置BasicDataSource对象