是否可以始终保持数据库连接打开? [英] Is it okay to always leave a database connection open?

查看:226
本文介绍了是否可以始终保持数据库连接打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个单用户桌面数据库应用程序,在业余时间,我总是不确定我做的设计选择。现在,按照它的样子,每当用户想要与数据库交互(这是一个本地SQLite数据库,所以一般只有一个用户曾经看到它),应用程序创建一个新的连接,做任何需要做的,然后关闭连接。在应用程序的一个执行过程中,大量的连接被创建和处理。

I'm working on a single-user desktop database application sort of thing in my spare time, and I'm always unsure about the design choices I'm making. Right now, as it stands, whenever the user wants to interact with the database (which is a local SQLite database, so generally only one user ever sees it at once), the application creates a new connection, does whatever it needs to do, and then closes the connection. Thereforee, over the course of one execution of the application, lots of connections are created and disposed of.

这通常是最好的应用程序应该在启动时打开连接,并只有在应用程序退出时关闭它吗?每个方法的优点/缺点是什么?

Is this generally the "best" way to go about it, or should the application open the connection at startup and only close it when the application exits? What are the advantages/disadvantages of each method?

推荐答案

我会说在这种情况下很好,一个用户和数据库托管在同一台机器上(更可能在相同的内存空间,我认为SQLite只是作为一个DLL与主应用程序加载)作为应用程序。不必不断地打开和关闭连接。

I would say it's fine in this case, since there will only ever be one user and the database is hosted on the same machine (more likely in the same memory space, as I think SQLite just loads as a DLL with the main application) as the application. Constantly opening and closing the connection is unnecessary.

一个可能的异常可能是,如果你需要让应用程序的多个线程同时访问数据库。然后您可以强制他们等待并共享单个连接对象,,您可以尝试为不同的线程创建新的连接。我从来没有在SQLite试过这个。这是一种情况,其中关闭主连接和打开/关闭多个连接可能更适合桌面应用程序。

One possible exception might be if you need to have multiple threads of your application accessing the database at the same time. Then you could either force them to wait and share a single connection object, OR you could try to create new connections for the different threads. I have never actually tried this in SQLite. This is one situation where closing the main connection and opening/closing multiple connections might be better for a desktop app.

对于Web应用程序或客户端/服务器桌面应用程序建议不要打开连接。

For web applications, or client/server desktop apps, I'd suggest against leaving connections open.

这篇关于是否可以始终保持数据库连接打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆