时间:2021-07-01 10:21:17 帮助过:28人阅读
1:第一种方式非常简单 c3p0.driverClass=com.mysql.jdbc.Driverc3p0.jdbcUrl=jdbc:mysql://localhost:3308/databasec3p0.user=rootc3p0.password=root 文件名字为:c3p0.properties(放在src目录下面) //程序我写的比较简单,可以用来测试执行配置。 packa
1:第一种方式非常简单
c3p0.driverClass=com.mysql.jdbc.Driver c3p0.jdbcUrl=jdbc:mysql://localhost:3308/database c3p0.user=root c3p0.password=root文件名字为:c3p0.properties(放在src目录下面)
package jdbc.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0 { public static void main(String[] args) throws SQLException { //数据库连接池默认会到classpath下去找数据库的配置。 ComboPooledDataSource data = new ComboPooledDataSource(); Connection conn = data.getConnection(); String sql = "select * from table"; PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)); } } }2:第二种方式非常灵活好用,也非常接近于我们平时的hibernate和struts的配置文件方式
root 1234 com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/database?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true 2 30 100 2 root root com.mysql.jdbc.Driver jdbc:mysql://localhost:3308/database?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true 2 30 100 2
package jdbc.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3p0JDBC { public static void main(String[] args) throws SQLException { System.setProperty("com.mchange.v2.c3p0.cfg.xml",System.getProperty("user.dir")+"/config/c3p0-config.xml"); //上面的配置文件3:这种配置是最不常用的,比较繁琐,就是把所有配置都写到程序里面来。//默认情况下 构造函数传空值。会去找默认配置 DataSource data = new ComboPooledDataSource(); //上面的配置文件 //如果构造函数中传值,则找到对应的配置。 DataSource data1 = new ComboPooledDataSource("database"); Connection conn = data.getConnection(); Connection conn1 = data1.getConnection(); String sql = "select * from table"; PreparedStatement pstmt = conn1.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)); } } }
可选择性使用
import com.mchange.v2.c3p0.*; ........ ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" ); cpds.setUser("dbuser"); cpds.setPassword("dbpassword"); cpds.setMaxStatements( 180 ); cpds.close();