关闭或不关闭数据库中的连接

关闭或不关闭数据库中的连接

问题描述:

我使用 SqlCE 处理 Windows-Mobile 和 Windows-CE,但我不知道该怎么做.

I work with Windows-Mobile and Windows-CE using SqlCE and I dont know what better to do.

要在程序打开时打开连接,运行任何查询的...更新...删除数据库并在程序关闭后关闭连接?

To open connection when the program open, run any query's... update...delete database and close the connection after the program close?

或者打开连接运行任何查询的..更新...删除数据库并立即关闭连接?

Or open connection run any query's..update...delete database and close the connection immediately?

很好.答案无处不在.以下是我从经验以及与 SQL Compact 团队互动中了解到的信息:

Nice. The answers are all over the place. Here's what I know from experience and interacting with the SQL Compact team:

  1. 关闭连接会刷新您所做的更改,否则引擎会在执行此操作之前等待刷新时间段.使用完毕后关闭连接是一个好主意,以确保您的更改真正进入商店.写入后和刷新前断电将丢失数据.
  2. 没有官方的连接池,但是打开第一个连接很昂贵(即慢),所有其他连接都很快.我从团队那里得到的建议是在应用程序启动时实际创建一个连接,然后让它保持打开状态.您实际上并不需要使用它,但保持打开状态会缓存大量连接信息,以便后续连接到同一商店的速度更快.
  1. Closing the connection flushes the changes you've made, otherwise the engine waits for the flush period before doing it. It's a good idea to close the connection when you're done using it to ensure that your changes actually go to the store. A power loss after a write and before a flush will lose data.
  2. There is no official connection pool, but opening the first connection is expensive (i.e. slow), all others are quick. The recommendation I got from the team is to actually create a connection when the app starts up and just leave it open. You don't actually need to use it, but keeping it open keeps a lot of connection info cached so that subsequent connections to the same store are quick.

所以答案实际上是两者兼而有之.

So the answer, actually, is both.

编辑

对于那些感兴趣的人,可以在 OpenNETCF ORM 库 中查看有关其工作原理的一个很好的示例.默认情况下,该库会创建一个维护"连接,该连接保持打开状态并用于执行模式查询之类的操作.所有其他数据操作使用它们自己的连接.您还必须选择将库配置为在 Store 的生命周期内重复使用单个连接,或者每次接触 store 时都使用新连接.在我使用默认设置的所有项目中,性能和行为一直是最好的(这就是我将其设为默认设置的原因).

For those interested, a good example of how this works can be seen in the OpenNETCF ORM library. The library, by default, creates a "maintenance" connection that remains open and is used for doing things like schema queries. All other data operations use their own connection. You also have to option to configure the library to reuse a single connection for the life of the Store, or to use a new connection every time it touches the store. Perfomance and behavior has always been best in all of my projects using the default (which is why I made it the default).