java 为什么我们需要 JDBC 的连接池?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16093054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why we need a connection pooling for JDBC?
提问by tarrsalah
What are the benefits of using a JDBC connection pooling tool like DBCPor c3p0?
in case of a small CRUDapplication with oneuser, can we just create oneconnection session as a singleton?
PS: I'm building a small javafx
application back-ended with tiny h2
database (5
tables).
PS:我正在构建一个javafx
带有小型h2
数据库(5 个表)后端的小型应用程序。
采纳答案by 0x6C38
From Jon Skeet's answer to What is the benefit of Connection and Statement Pooling?:
来自 Jon Skeet对连接和语句池的好处是什么的回答?:
Creating a network connection to a database server is (relatively) expensive. Likewise asking the server to prepare a SQL statement is (relatively) expensive.
Using a connection/statement pool, you can reuse existing connections/prepared statements, avoiding the cost of initiating a connection, parsing SQL etc.
创建到数据库服务器的网络连接(相对)昂贵。同样,要求服务器准备 SQL 语句是(相对)昂贵的。
使用连接/语句池,您可以重用现有的连接/准备好的语句,避免启动连接、解析 SQL 等的成本。
And the following, from Kent Boogaart's answer:
以下内容来自Kent Boogaart 的回答:
I am not familiar with c3p0, but the benefits of pooling connections and statements include:
Performance. Connecting to the database is expensive and slow. Pooled connections can be left physically connected to the database, and shared amongst the various components that need database access. That way the connection cost is paid for once and amortized across all the consuming components.
Diagnostics. If you have one sub-system responsible for connecting to the database, it becomes easier to diagnose and analyze database connection usage.
Maintainability. Again, if you have one sub-system responsible for handing out database connections, your code will be easier to maintain than if each component connected to the database itself.
我对 c3p0 不熟悉,但是池化连接和语句的好处包括:
表现。连接到数据库既昂贵又缓慢。池连接可以物理连接到数据库,并在需要数据库访问的各种组件之间共享。这样,连接成本一次性支付,并在所有消费组件之间分摊。
诊断。如果您有一个子系统负责连接数据库,那么诊断和分析数据库连接使用情况就会变得更加容易。
可维护性。同样,如果您有一个子系统负责分发数据库连接,那么您的代码将比每个组件都连接到数据库本身更容易维护。
回答by JS.
Creating connections is costly and it doesn't make sense to create a new connection for each transaction that might only take a few milliseconds. Managing database connections in a pool means that applications can perform database transactions in a way that avoid the connection creation time (The connections still need to be created, but they are all created at startup). The downside is that if all connections are in use, and another connection is required, the requesting thread will have to wait until a connection is returned to the pool.
创建连接的成本很高,而且为每个可能只需要几毫秒的事务创建一个新连接是没有意义的。管理池中的数据库连接意味着应用程序可以通过避免连接创建时间的方式执行数据库事务(连接仍然需要创建,但它们都是在启动时创建的)。缺点是如果所有连接都在使用中,并且需要另一个连接,则请求线程将不得不等待连接返回到池中。