日期:2014-05-16  浏览次数:20521 次

c3p0 通过c3p0.properties配置文件 连接数据库
C3P0连接说明文档:http://www.mchange.com/projects/c3p0/#what_is

使用需要2个包:c3p0-****.jar 和mchange-commons-java-**.jar
[color=green]
c3p0.properties 文件
    c3p0.JDBC.url=jdbc:mysql://localhost:3306/ms_cms?characterEncoding=utf8
    c3p0.DriverClass=com.mysql.jdbc.Driver
    c3p0.user=root
    c3p0.pwd=

    c3p0.acquireIncrement=3
    c3p0.idleConnectionTestPeriod=60
    c3p0.initialPoolSize=10
    c3p0.maxIdleTime=60
    c3p0.maxPoolSize=20
    c3p0.maxStatements=100
    c3p0.minPoolSize=5

public Connection dd() throws FileNotFoundException, IOException, PropertyVetoException, SQLException{
	
		Properties pr = new Properties();
		//获得src下的c3p0.properties的路径
		String c3p0Properties = this.getClass().getClassLoader().getResource("c3p0.properties").getPath();
		//路径的编码是UTF-8
		c3p0Properties = URLDecoder.decode(c3p0Properties, "utf-8");
		//得到文件c3p0.properties文件
		java.io.File c3p0File = new java.io.File(c3p0Properties);
		//读取c3p0文件的内容
		pr.load(new FileInputStream(c3p0File));
		
//		pr.save(new FileOutputStream(c3p0File), null);
		//使用c3p0操作数据库
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		//加载数据驱动
		cpds.setDriverClass(pr.getProperty("c3p0DriverClass"));
		//连接特定的数据库
		cpds.setJdbcUrl(pr.getProperty("c3p0.JDBC.url"));
		//数据库用户名
		cpds.setUser(pr.getProperty("c3p0.user"));
		//数据库用户密码
		cpds.setPassword(pr.getProperty("c3p0.pwd"));
		//获得连接
		Connection conn = cpds.getConnection();
		return conn;
	}
[/color]