如何检查 Android SQLite 数据库中是否存在表? [英] How does one check if a table exists in an Android SQLite database?

查看:27
本文介绍了如何检查 Android SQLite 数据库中是否存在表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个android应用程序需要检查数据库中是否已经有记录,如果没有,处理一些事情并最终插入它,如果数据确实存在,只需从数据库中读取数据.我正在使用 SQLiteOpenHelper 的子类来创建和获取 SQLiteDatabase 的可重写实例,我认为如果表不存在,它会自动处理创建表(因为执行此操作的代码在 onCreate(...) 方法).

I have an android app that needs to check if there's already a record in the database, and if not, process some things and eventually insert it, and simply read the data from the database if the data does exist. I'm using a subclass of SQLiteOpenHelper to create and get a rewritable instance of SQLiteDatabase, which I thought automatically took care of creating the table if it didn't already exist (since the code to do that is in the onCreate(...) method).

但是,当表尚不存在,并且在我拥有的 SQLiteDatabase 对象上运行的第一个方法是调用 query(...) 时,我的 logcat 显示错误I/Database(26434): sqlite返回:错误代码 = 1,msg = 没有这样的表:appdata",果然没有创建 appdata 表.

However, when the table does NOT yet exist, and the first method ran upon the SQLiteDatabase object I have is a call to query(...), my logcat shows an error of "I/Database(26434): sqlite returned: error code = 1, msg = no such table: appdata", and sure enough, the appdata table isn't being created.

有什么想法吗?

我正在寻找一种方法来测试表是否存在(因为如果不存在,则数据肯定不在其中,并且在写入之前我不需要读取它,这似乎正确创建表),或者确保它被创建并且是空的,及时第一次调用 query(...)

I'm looking for either a method to test if the table exists (because if it doesn't, the data's certainly not in it, and I don't need to read it until I write to it, which seems to create the table properly), or a way to make sure that it gets created, and is just empty, in time for that first call to query(...)

编辑
这是在以下两个答案之后发布的:
我想我可能已经发现了问题.我出于某种原因决定应该为每个表创建一个不同的 SQLiteOpenHelper,即使它们都访问相同的数据库文件.我认为重构该代码以仅使用一个 OpenHelper,并在其 onCreate 中创建两个表可能会更好...

EDIT
This was posted after the two answers below:
I think I may have found the problem. I for some reason decided that a different SQLiteOpenHelper was supposed to be created for each table, even though both access the same database file. I think refactoring that code to only use one OpenHelper, and creating both tables inside it's onCreate may work better...

推荐答案

是的,事实证明我编辑中的理论是正确的:导致 onCreate 方法无法运行的问题是 SQLiteOpenHelper 对象应该引用数据库,而不是每个表都有一个单独的.将两个表打包成一个 SQLiteOpenHelper 解决了这个问题.

Yep, turns out the theory in my edit was right: the problem that was causing the onCreate method not to run, was the fact that SQLiteOpenHelper objects should refer to databases, and not have a separate one for each table. Packing both tables into one SQLiteOpenHelper solved the problem.

这篇关于如何检查 Android SQLite 数据库中是否存在表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆