SQlite表升级困难
我有一个使用名为 ANIMAL 的工作表运行的应用程序。首次创建此表时,它仅包含 _id 和animal_name 列。
现在我正在尝试扩展它,包括animal_biography列,但是我遇到了一点困难。起初我以为我只是升级我的CREATE_TABLE语句以包含动物生物:
private static final String DATABASE_CREATE =
"create table " + ANIMALS_TABLE +
" (_id integer primary key autoincrement, " +
"animal_name text not null, " +
"biography text not null);";
但是,看看它告诉的logcat我尝试插入列传记时不存在。
现在,我尝试使用 onUpgrade()
并包含代码来升级数据库,
db.execSQL("ALTER TABLE" + DATABASE_NAME);
db.execSQL(DATABASE_CREATE);
但这也不能解决问题。有人对如何解决这个问题有任何指示吗?
I have an application running with a working table called ANIMAL. Upon first creating this table it consisted simply of _id and animal_name columns.
Now I am trying to expand on it, including a animal_biography column, however I am having a little difficulty.At first I thought I was just a case of upgrading my CREATE_TABLE statement to include the animal bio:
private static final String DATABASE_CREATE =
"create table " + ANIMALS_TABLE +
" (_id integer primary key autoincrement, " +
"animal_name text not null, " +
"biography text not null);";
however, looking at the logcat it tells me the column biography does not exist when trying to insert into it.
Now, I have tried to upgrade the database by using the onUpgrade()
and including the code
db.execSQL("ALTER TABLE" + DATABASE_NAME);
db.execSQL(DATABASE_CREATE);
but this is not solving the problem either. Does anyone have any pointers on how to go about fixing this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用
SQLiteOpenHelper
,则可以轻松升级表。您需要实现onCreate
和onUpgrade
方法,并在类构造函数中提供数据库的当前版本。更新表时只需增加数据库版本号,在onCreate
方法中指定新表创建查询,并将ALTER TABLE
放入onUpgrade
方法以更新以前的版本表的。当Android检测到数据库版本不匹配时,会自动调用onUpgrade
方法。请参阅示例:这种升级方法是在不丢失用户数据的情况下修改表的正确方法,特别是如果应用程序已经向公众发布的话。
If you are using
SQLiteOpenHelper
it's easy to upgrade a table. You need to implement methodsonCreate
andonUpgrade
and provide current version of your database in class constructor. When updating your table just increment database version number, specify new table creation query inonCreate
method and putALTER TABLE
toonUpgrade
method to update previous version of table. When Android detects database version mismatch, it will callonUpgrade
method automatically. See the example:This method of upgrading is the correct way to modify tables without losing user data, especially if the app had been released to public already.