域对象中的 iPhone SQLite 连接 - 每次都关闭?

发布于 2024-08-28 01:33:01 字数 170 浏览 3 评论 0原文

我有一个我认为是使用 SQLite 的小型 iPhone 应用程序。

有一个单例域对象从 SQLite 数据库获取数据。

是为每个请求创建并打开 SQLite 连接更好,还是打开数据库一次并在应用程序运行期间保留它更好。

该应用程序存在的原因是域对象,因此其他对象不需要数据库。

I have what I would consider a small sized iPhone app that uses SQLite.

There is a singleton domain object which gets data from a SQLite database.

Is it better to create and open the SQLite connection for each request, or to open the DB once and hold on to it for the duration of the app.

The app's reason for being is the domain object so other objects will not need the DB.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九局 2024-09-04 01:33:01

我通常会只打开数据库一次,并在单例对象中保存对它的引用。至于这是否会产生很大的性能差异将取决于您发出请求的频率。例如,如果您请求 tableView 中每个单元格的数据,我希望仅打开数据库一次就会产生很大的差异。

通过仅打开一次,您还可以在单​​例中保留对准备好的 SQL 语句的引用,这样您就不需要每次都编译它们。每次发出请求时,首先检查是否已编译准备好的语句。如果没有,您可以调用 sqlite3_prepare_v2 来编译它并将生成的语句保存在您的单例中。

if (request_stmt == nil) {
    const char *sql = "SELECT ...... WHERE xxx LIKE ?";
    sqlite3_prepare_v2(sqldb, sql, -1, &request_stmt, NULL);
}

当你释放你的单例时,你可以通过调用 sqlite3_finalize 来释放这些语句。

I would generally go with opening the database just once and holding a reference to it in your singleton object. As to whether this makes a big performance difference will depend on how often you make requests. If you are requesting data for each cell in a tableView for example I would expect that opening the database only once would make a big difference.

By opening only once you could also keep references in your singleton to prepared SQL statements so that you do not need to compile them each time. Each time you make a request first check if you have the prepared statement already compiled. If not you make a call to sqlite3_prepare_v2 to compile it and save the resulting statement in your singleton.

if (request_stmt == nil) {
    const char *sql = "SELECT ...... WHERE xxx LIKE ?";
    sqlite3_prepare_v2(sqldb, sql, -1, &request_stmt, NULL);
}

You can release these statements by calling sqlite3_finalize when you release your singleton.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文