一个人怎么检查,如果一个表存在于Android的SQLite数据库? [英] How does one check if a table exists in an Android SQLite database?

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

问题描述

我有一个Android应用程序,需要检查是否有已在数据库中的记录,如果没有,过程中的一些东西,并最终将其插入,并简单地从数据库中读取数据,如果数据确实存在。我使用SQLiteOpenHelper的子类来创建并获得SQLiteDatabase,我想自动把创建表,如果它不存在(因为code这样做是在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对象我有一个电话查询(...),我的logcat显示I /数据库的错误(26434):源码返回:错误code = 1,味精=没有这样的表:应用程序数据,果然,该应用程序数据表不被创建

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.

为什么任何想法?

我在找任何一个方法来测试,如果表存在(因为如果不是这样,数据的肯定不是它,我不需要看它,直到我写,这似乎创建表正确),还是有办法,以确保它被创建的,仅仅是空的,在时间上为第一次调用查询(...)

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本来是要为每个表创建的,即使这两个访问同一个数据库文件。我认为重构是code到只使用一个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天全站免登陆