一 配置
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 定义数据源Bean,使用C3P0数据源实现 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- 指定连接数据库的驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<!-- 指定连接数据库的URL -->
<property name="jdbcUrl" value="jdbc:mysql://localhost/spring"/>
<!-- 指定连接数据库的用户名 -->
<property name="user" value="root"/>
<!-- 指定连接数据库的密码 -->
<property name="password" value="32147"/>
<!-- 指定连接数据库连接池的最大连接数 -->
<property name="maxPoolSize" value="200"/>
<!-- 指定连接数据库连接池的最小连接数 -->
<property name="minPoolSize" value="2"/>
<!-- 指定连接数据库连接池的初始连接数 -->
<property name="initialPoolSize" value="2"/>
<!-- 指定连接数据库连接池的连接的最大空闲时间 -->
<property name="maxIdleTime" value="200"/>
</bean>
</beans>
二 测试类
package lee;
import javax.sql.DataSource;
import java.sql.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanTest
{
public static void main(String[] args)
throws Exception
{
// 实例化Spring容器。Spring容器负责实例化Bean
ApplicationContext ctx =
new ClassPathXmlApplicationContext("beans.xml");
// 获取容器中id为dataSource的Bean
DataSource ds = ctx.getBean("dataSource", DataSource.class);
// 通过DataSource来获取数据库连接
Connection conn = ds.getConnection();
// 通过数据库连接获取PreparedStatement
PreparedStatement pstmt = conn.prepareStatement(
"insert into news_inf values(null , ? , ?)");
pstmt.setString(1 , "疯狂Java联盟成立了");
pstmt.setString(2 , "疯狂Java地址:www.crazyit.org");
// 执行SQL语句
pstmt.executeUpdate();
// 清理资源,回收数据库连接资源。
if (pstmt != null)pstmt.close();
if (conn != null)conn.close();
}
}
三 测试结果