如何在JDBC中建立连接池? [英] How to establish a connection pool in JDBC?

查看:33
本文介绍了如何在JDBC中建立连接池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能提供有关如何建立 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.sqljava.sql 没有池化连接实现吗?为什么不最好使用这些?

Update: Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?

推荐答案

如果您需要一个独立的连接池,我的首选方法是 C3P0 超过 DBCP(我在这个以前的答案),我刚刚有重负载下 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 检索数据源:

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中建立连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆