在android中打开和关闭数据库连接?(open and close database Connection in android?)

编程入门 行业动态 更新时间:2024-10-09 05:25:01
在android中打开和关闭数据库连接?(open and close database Connection in android?)

我搜索了很多问题,但我没有得到正确答案。 在活动生命周期中打开和关闭数据库的最佳方法是什么。 请有人帮我正确答案。

提前致谢。

i searched lot questions but i didnt get correct answer. What is the best way to open and close the database in activity lifecycle. please someone help me with correct answer.

Thanks in advance.

最满意答案

使用db=DatabaseHelper.getInstance(context)使用Singleton模式和访问。 它保证在整个应用程序生命周期中只存在一个数据库帮助程序。

public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper sInstance; private static final String DATABASE_NAME = "database_name"; private static final String DATABASE_TABLE = "table_name"; private static final int DATABASE_VERSION = 1; public static synchronized DatabaseHelper getInstance(Context context) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. if (sInstance == null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } /** * Constructor should be private to prevent direct instantiation. * make call to static method "getInstance()" instead. */ private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }

并访问使用:

db=DatabaseHelper.getInstance(this);

如果需要,您还可以在catch块中关闭数据库连接。 我希望它有所帮助。

Use Singleton pattern and access using db=DatabaseHelper.getInstance(context). It guarantees that only one database helper will exist across the entire application lifecycle.

public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper sInstance; private static final String DATABASE_NAME = "database_name"; private static final String DATABASE_TABLE = "table_name"; private static final int DATABASE_VERSION = 1; public static synchronized DatabaseHelper getInstance(Context context) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. if (sInstance == null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } /** * Constructor should be private to prevent direct instantiation. * make call to static method "getInstance()" instead. */ private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }

And access using :

db=DatabaseHelper.getInstance(this);

And also you can close database connection in catch block if needed. I hope it help.

更多推荐

本文发布于:2023-08-07 16:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465283.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库连接   open   android   Connection   database

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!