Is it acceptable to keep a db connection open for the life of the page?

前端 未结 10 1942
执念已碎
执念已碎 2021-01-18 07:11

Everybody knows that you should close a connection immediately after you finish using it.

Due to a flaw in my domain object model design, I\'ve had to leave the conn

相关标签:
10条回答
  • 2021-01-18 07:27

    You should certainly keep the connection open across the lifetime of the page, if you're doing multiple queries during it. Generally, one re-uses connections across many pages, actually.

    0 讨论(0)
  • 2021-01-18 07:34

    No, it is not OK.

    If your application will ever need to grow or scale, you'll want to fix this issue. By holding that connection open you're reducing your ability to scale. Keep in mind that open connections take up memory on the server, memory on the client, hold open locks, etc.

    0 讨论(0)
  • 2021-01-18 07:40

    It's not ideal but I wouldn't re-write my application over it. Unless your page is doing a large amount of time-consuming work in various methods, the whole page lifecycle should execute quickly. In practice it may just mean that your connection object is open a few milliseconds longer than it would have been otherwise. That might be significant in some scenarios, but it doesn't sound like it would be in your case.

    0 讨论(0)
  • 2021-01-18 07:46

    Of course you can keep them open, but no no. Close it after use in finally blocks. A fair trade off from "after every single use" is to close it after every block of use, if you're apt to run a stored proc, update a column, then delete some other row, you could open/close around those three operations, presuming they're all wrapped in a try/catch/finally.

    0 讨论(0)
  • 2021-01-18 07:46

    I find it convenient to keep the connection open when using ORM (Open Session in View) so that after an initial eager fetch, other data can be lazily loaded as needed. This works well when page response times are reasonable so as not to tie up connections.

    0 讨论(0)
  • 2021-01-18 07:47

    Yes, it is ok.

    Closing the connection as soon as you can is a best practice for preventing orphan open connections, but if you are sure that the connection is being close, there is nothing wrong with that.

    0 讨论(0)
提交回复
热议问题