简体   繁体   中英

The reason that you might want two or more instances for same DB connection?

I am trying to think of a scenario that you need more than one instances of DB connection.

Normally, DB connection is one singleton object used for everything. But what's the reason that you might want to create another instance of the same class. (I read it somewhere.)

Trying to understand this, two instances of DB connections would seem very risky to cause conflict when writing to DB. But would be faster when reading? (maybe this is one reason?)

Maybe DB connection is not a very good example. You can give me other scenario if you know anywhere creating more than one instance of a Singleton class make sense.

A DB connection pool may be a singleton, but of course you would want to have more than one DB connection available at the same time for some applications. Think of a web server. Why wouldn't you want to be able to process concurrent requests by multiple users? And databases are usually quite good at making sure this does not cause any tragic conflicts (there is transaction isolation).

You may need to be more specific on local app/embedded DB vs Servers.

But, if you have a application server (IIS, Apache etc...) that talks to a database server (SQL Server, Oracle etc...), you would want concurrency and multiple connections active at a time. You want concurrency since it's a server handling many concurrent requests and sql servers should be able to handle that. Serializing all database activity on a server would be catastrophic.

Concerning DB connections, with most db access technologies, they offer connection pooling . So you simply open the connection, do your work and then close. That acquires and releases the connections back into a pool so they don't have to be recreated.

Re: "Two instances of DB connections would seem very risky to cause conflict when writing to DB"

Most database servers also offer control when dealing with concurrency. For example with sql server, you have locking and isolation levels

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM