问题描述
任何人都可以提供有关如何建立JDBC连接池的示例或链接吗?
Can anybody provide examples or links on how to establish a JDBC connection pool?
从搜索谷歌我看到很多不同的方法,这是相当混乱的。
From searching google I see many different ways of doing this and it is rather confusing.
最终我需要代码返回 java.sql.Connection
对象,但我无法入门..欢迎任何建议。
Ultimately I need the code to return a java.sql.Connection
object, but I am having trouble getting started..any suggestions welcome.
更新不 javax.sql
或 java.sql
汇集了连接实现?为什么不最好使用这些?
Update: Doesn't javax.sql
or java.sql
have pooled connection implementations? Why wouldn't it be best to use these?
推荐答案
如果你需要一个独立的连接池,我的偏好是超过(我在这里提到过),我在DBCP负载过重时遇到了太多问题。使用C3P0很简单。来自:
If you need a standalone connection pool, my preference goes to C3P0 over DBCP (that I've mentioned in this previous answer), I just had too much problems with DBCP under heavy load. Using C3P0 is dead simple. From the 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:
But if you are running inside an application server, I would recommend to use the built-in connection pool it provides. In that case, you'll need to configure it (refer to the documentation of your application server) and to retrieve a DataSource via JNDI:
DataSource ds = (DataSource) new InitialContext().lookup("jdbc/myDS");
这篇关于如何在JDBC中建立连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!