我正在使用java在android中创建一个简单的android应用程序。我有一个名为的名为user的表的空间数据库数据库,该表具有四列名称、职业、年龄、description,并且我已经使用我在studio中创建的数据库进行了预填充。
现在,我想在表上添加一个列姓氏,但是我想要删除所有预先填充的数据,然后用一个包含姓氏的新数据库重新填充表。
起初,我想使用自动迁移,然后添加一个新列。但我不知道如何删除所有现有数据并重新填充数据库。
我想删除现有的数据,因为我想更改列description.中的所有信息。另外,与列名称一样,它现在包含全名,在某些情况下,它包含行"name surname“,还有一些类似于”姓氏“、”e.x“、威尔史密斯、"Smith Will”的行。现在,我希望将名称和姓氏分别列为名称、和姓氏。
有人能给我推荐点什么吗?提前谢谢你
发布于 2021-10-06 16:05:03
AutoMigration将无法处理修改数据本身的问题。因此,您必须手动完成该操作,从而使用破坏性迁移。
下面是一个例子(可以看到实际的例子)
- an SQLite database has, as part of it's header, a user\_version number (offset 60 for 4 bytes). It is comparing this to the version passed to Room that determines the migration/auto migration. As is seen changing this is critical if migrating.
- If developing you could just start from the changed database by making the changes to the database and the App and uninstalling the App. No need to play with version numbers.
:-
@Entity
class User {
@PrimaryKey
@NonNull
String name;
String profession;
int age;
String description;
/* ADDED FOR V2 */
String surname;
}
1. locate the **createAllTables** method and then the SQL for the User table. Make a note of the SQL and the definition for the new column e.g. -surname TEXT
在
ALTER TABLE user ADD COLUMN surname TEXT;
,其中列关键字后面的文本/代码与上面提到的SQL完全相同(您可以包括或省略列名周围的封闭内容,它们很难在SQLite中显示)。
1.
nulls.
1.
然后,
PRAGMA user_version;
(检查当前版本)然后
PRAGMA user_version = 2;
(以更改版本(猜测2))然后,
PRAGMA user_version;
(以检查该版本现在为2)1.
@Database类中的
1. change the database version to 2
2. add the following to the the databaseBuild :-
1. either `.fallbackToDestructiveMigrationFrom(1)` if going from 1 to 2
2. or `.fallbackToDestructiveMigration()` (not as safe but more encompassing)
1.
https://stackoverflow.com/questions/69473217
复制相似问题