同时在同一个数据库上打开多个连接是明智的还是我应该避免这种情况?

Is it smart to open multiple connections on the same database at the same time or shall I avoid that?

我正在创建一个需要连接数据库的应用程序。我经常需要做的一件事是通过 groupId 从数据库中获取用户列表。

在我需要这些信息的每一种方法中,我都创建了一个命令来检索信息,而不是(我在学校学到的)有一个单独的方法来获取信息并将其传递下去。

我这样做是因为我想设置尽可能少的连接,同时打开。但是,我不确定哪种方式最好。我在 Internet 上搜索了答案,但没有找到任何答案。执行此操作的最佳方法是什么?

如果我对这个问题还不够清楚,尽管问。

同时打开同一个数据库的两个连接是明智的还是我应该避免这种情况?

Yeah, its smart to set up multiple connection using connection pool for many reasons. Using a connection/statement pool, you can reuse existing connections/prepared statements, avoiding the cost of initiating a connection, parsing SQL etc.

Opening/Closing database connections is an expensive process and hence 

connection pools improve the performance of execution of commands on a database for which we maintain connection objects in the pool. It facilitates 

reuse of the same connection object to serve a number of client requests. 

Every time a client request is received, the pool is searched for an 

available connection object and it's highly likely that it gets a free 

connection object. 
  1. 我建议你,实现单例模式(或任何其他模式)并在你的项目中设置一个连接池。

  2. 做一个class"DatabaseConnection",你可以有不同的方法,其中之一就是你指出的getAllValues() {}

  3. 您可以实现不同的模式AbstractFactory、DAO 和单例。单身人士更适合初学者,单身人士也不是那么容易。请在这里参考更多关于单例的信息: What is an efficient way to implement a singleton pattern in Java?

  4. Need Code to create Connection Pool in java

  5. 我在HIKARI上做过连接池,如果你搜索的话还有其他的。 Why we need a connection pooling for JDBC?

连接池的根本原因是什么?

假设您像我一样为我的学生项目构建了一个网站,电影租赁申请。我的教授走过来问了我一个让我大吃一惊的问题。

您只有一个 class(对象)用于数据库连接(单例),如果一百万用户同时请求一些结果 obj.getAllUser() 怎么办。您如何处理这种情况?然后他离开了

I was baffled and I immediately went on Google and typed the same problem and saw one Whosebug post...connection pool is the answer. I went straight to him and said I will handle this using a connection pool. He was impressed and I got 'A' in his class. Hope this helps.