简体   繁体   中英

Managing database connections in .NET - Keeping a connection alive

I have a project which heavily relies on a database. Basically, every action in the project requires a query to the database.

The project follows the Three-tier architecture , and at my Data layer I have an SqlConnection instance as a data member for interacting with the database.

The problem is that sometimes the connection is being disconnected for no apparent reason.
My question is, how can I make sure the connection stays alive?
one suggestion I got so far is to send " keep-alive-query " periodically. something like SELECT 1 .

I would also appreciate any insights you have about what may cause this periodical disconnection.

From this SO thread I understand that keeping the connection as a data member might not be the best practice, but this is the current situation, and I would prefer to avoid changing it at this point.

It would be better if you could not keep the connection alive. It's not necessary in modern databases to do that. When you need to access the database, you should open a connection and as soon as you're done, close it.

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