如何更新SQLite数据库,而不是失去所有现有的数据? [英] How to update an SQLite Database and NOT lose all existing data?

查看:719
本文介绍了如何更新SQLite数据库,而不是失去所有现有的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加一个表来我的应用程序的的SQLite数据库。我所有的语法有精,不是问题。但我不得不适当创造了一些麻烦的新表。我添加了新的表......

I'm adding a table to my app's SQLite DB. All my syntax there is fine, not the issue. But I'm having some trouble getting the new table to be created properly. I added the new table....

@Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
            db.execSQL(CREATE_REQUESTS);
            db.execSQL(CREATE_OVERRIDE);
        }

我在创建方法。我有3个表。当我更新的版本号,我得到了一个错误说表请求(指CREATE_REQUESTS)已创建。看看我的onUpgrade方法...

My on create method. I have 3 tables. When I updated the version number, I got an error saying "table requests (referring to CREATE_REQUESTS) has already been created." A look at my onUpgrade method...

@Override 
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }

使我明白,行 db.execSQL(DROP TABLE IF EXISTS接触),这是指我DATABASE_CREATE表中onCreate方法,用于删除旧表,然后下一行,的onCreate(DB); 重新创建。我没有添加请求到该execSQL线,这是什么原因造成的错误。下面是这个问题:我宁愿不丢失数据的两个表我已经有研究。有没有办法来添加表像我试图做的,而不是失去所有旧的数据?谢谢你。

Led me to understand that the line db.execSQL("DROP TABLE IF EXISTS contacts"), which refers to my DATABASE_CREATE table in the onCreate method, is used to drop the old table, then the next line, onCreate(db); recreates it. I did not add requests into that execSQL line, which is what caused the error. Here is the issue: I would rather not lose the data in the two tables I already have. Is there a way to add a table like I am trying to do, and not lose all the old data? Thanks.

推荐答案

您可以做任何你想要的 onUpgrade 。您可以使用 ALTER 来添加新列到你的表。

You can do anything you want in onUpgrade. You can use ALTER to add new columns to your table.

最坏的情况,如果你的模式是完全的,完全不同的,你必须创建新的表,填充它使用旧表中的数据,然后删除旧表。

Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.

在任何情况下, onUpgrade 被设计为允许在不丢失任何数据的平滑升级。这只是由你来正确地实现了。

In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.

这篇关于如何更新SQLite数据库,而不是失去所有现有的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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