我正在尝试使用 SQFlite plugin 了解数据库操作。对于 flutter 。在 usage recommendation docs ,作者说:
The API is largely inspired from Android ContentProvider where a typical SQLite implementation means opening the database once on the first request and keeping it open.
Personally I have one global reference Database in my Flutter application to avoid lock issues. Opening the database should be safe if called multiple times.
Keeping a reference only in a widget can cause issues with hot reload if the reference is lost (and the database not closed yet).
这是否意味着我创建了一个打开数据库连接的单例类(如 here )然后我从不关闭它?也就是说,我从不这样做:
await database.close();
我过去在使用 Android SQLite 时遇到过并发问题(如 here 所述),因此我通常使用内容提供程序来解决这个问题。但是,我只是在使用它时并没有真正了解内容提供商在幕后所做的事情。保持与数据库的单个连接是否会做同样的事情?应用退出时是否需要关闭数据库? This user好像觉得没关系。
最佳答案
我没有关闭数据库,也没有遇到任何问题,但最好的做法是关闭所有不需要的数据库连接。
您可以通过重写 onInitState()
来初始化 DB,您可以在其中调用创建 DB 的函数,并通过重写 onDispose()
来关闭您可以调用 的函数>db.close()
或者,您可以为每个查询打开/关闭连接,但这会增加额外的处理开销,并且没有必要这样做,尤其是在您进行频繁的数据库调用时。
更详细的信息可以引用这篇文章: https://medium.com/@greg.perry/flutter-and-sqlite-f72878bc5859
关于sqlite - 不使用 Flutter 的 SQFlite 关闭数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54055106/