您的位置:首页 > 编程语言 > Java开发

Spring使用c3p0数据源

2016-03-11 17:02 344 查看
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 -->
<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-3.0.xsd"> 
<!-- 定义数据源Bean,使用C3P0数据源实现 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 指定链接数据库的驱动 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<!-- 指定链接数据库的URl -->
<property name="jdbcUrl" value="jdbc:mysql://localhost/mytest1"/>
<!-- 指定数据库的用户名 -->
<property name="user" value="root"/>
<!-- 指定链接数据库的密码 -->
<property name="password" value=""/>
<!-- 指定链接数据库链接池的最大连接数 -->
<property name="maxPoolSize" value="40"/>
<!-- 指定链接数据库链接池的最大连接数 -->
<property name="minPoolSize" value="1"/>
<!-- 指定链接数据库链接池的初始化连接数 -->
<property name="initialPoolSize" value="1"/>
<!-- 指定链接数据库链接池的最大空闲时间 -->
<property name="maxIdleTime" value="20"/>
</bean>
</beans>
/**
*
*/
/**
* @author c
*
*/
package qi;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.DataSource;

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("bean.xml");
//通过Bean id获得Bean实例,强制类型转换为DataSource
DataSource ds = ctx.getBean("dataSource", DataSource.class);

//通过DataSource来获取数据库链接
Connection conn = ds.getConnection();
//通过数据库链接获取PreparedStatement
PreparedStatement pstmt = conn.prepareStatement("insert into user values(?,?)");
pstmt.setString(1, "java4S");
pstmt.setString(2, "dizhi ");
//执行SQL语句
pstmt.executeUpdate();

//清理资源,回收数据库链接资源
if(pstmt != null)pstmt.close();
pstmt = conn.prepareStatement("select * from user where userId = ?");
pstmt.setString(1, "chc0618");
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString("userId")+" , 密码:"+rs.getString("uPS") );
}
if(conn != null)conn.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: