谁能提供有关如何建立 JDBC 连接池的示例或链接?
从谷歌搜索中,我看到了许多不同的方法,这很令人困惑。
最终我需要代码来返回一个 java.sql.Connection
对象,但我无法开始使用..欢迎任何建议。
更新: javax.sql
或 java.sql
没有池化连接实现吗?为什么不最好使用这些?
最佳答案
如果您需要一个独立的连接池,我的首选是 C3P0超过 DBCP (我在 previous answer 中提到过),我只是在重负载下遇到了太多 DBCP 问题。使用 C3P0 非常简单。来自 documentation :
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
// The DataSource cpds is now a fully configured and usable pooled DataSource
但如果你在应用服务器中运行,我建议使用它提供的内置连接池。在这种情况下,您需要对其进行配置(请参阅应用服务器的文档)并通过 JNDI 检索 DataSource:
DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
关于java - JDBC中如何建立连接池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835090/