Android中能不能判断一个数据库是create来的,还是open来的?
阿神
阿神 2017-04-17 17:28:58
0
5
403

先简单说一下我想实现的功能,就是创建数据库的时候,同时也会创建一个表,然后就往表里插入数据;之后,就是打开数据库,然后对表的数据进行更新。
所以我想知道这个数据库是创建来的,还是打开来的,好让我执行不同的操作。
而我创建数据库的方法是继承SQLiteOpenHelper类和实现getWritableDatabase方法。具体如下图:

这样的话,我就打算判断这个mSqLiteDatabase(这是SQLiteDatabase的一个实例对象,截图没放出来)是创建来的,还是打开来的。因为我看文档里说,上图的方法是:存在该数据库就打开,不存在就创建。而getWritableDatabase方法是返回一个数据库的对象。所以我就这样瞎想,不知道可不可以判断。如果不行的话,有没有其它可替代的方法。

阿神
阿神

闭关修行中......

reply all(5)
伊谢尔伦

According to your needs, it doesn’t matter whether it is newly created or opened. After opening it, check whether there is data, update it if there is, and create a new one if it doesn’t.

巴扎黑

Just create the table in the DatabaseHelperonCreate(SQLiteDatabase) method. This method will be called when the database is first created. Then you just need to insert the data

洪涛

I have always used xutils to operate the database. This encapsulates the database very well and is very simple.
There is a db.openorupdate method inside, which will automatically compare the data to determine whether to open or update.

If you use the native Android method, there is no need to judge. You only need to confirm whether there is new data, and if so, just insert it

小葫芦

OnCreate will only be called when the database is opened for the first time. At this time, you can just create the table. OnCreate will not be called the next time you open it.

PHPzhong

First of all, thank you very much for your answers. According to xiluoduyu's answer, it is indeed possible to achieve the function I want. If I change my thinking, it is indeed possible. But in the process of asking this question, I discovered that the problem described in the title is actually what I want to know and understand. Maybe this question is weird, or even has no answer, so I’ll make a note first and come back to it later. Thank you!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template