如何将新的 table 添加到 sqlite?
How to add new table to sqlite?
我需要为现有的 table 添加一个新的列名 id INTEGER AUTOINCREMENT
和一个新的 table。如何使用'onUpgrade'?是否需要更改版本号?
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "HelperDatabase.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate, onUpgrade: _onUpgrade);
return theDb;
}
如何使用_onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
}
是否也需要添加列?
void _onCreate(Database db, int version) async {
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
要从旧版本更新您的数据库,您应该将 version
更改为 2
。
您应该像下面这样更改 onCreate
和 onUpdate
。
// This is called for new users who have no old db
void _onCreate(Database db, int version) async {
// if `AssetAssemblyTable` has a new column in version 2, add the column here.
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
)
await db.execute("CREATE TABLE NewTable...") // create new Table
}
// This is called for existing users who have old db(version 1)
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
// In this case, oldVersion is 1, newVersion is 2
if (oldVersion == 1) {
await db.execute("ALTER TABLE AssetAssemblyTable...") // add new column to existing table.
await db.execute("CREATE TABLE NewTable...") // create new Table
}
}
更多示例如下
https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md
我需要为现有的 table 添加一个新的列名 id INTEGER AUTOINCREMENT
和一个新的 table。如何使用'onUpgrade'?是否需要更改版本号?
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "HelperDatabase.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate, onUpgrade: _onUpgrade);
return theDb;
}
如何使用_onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
}
是否也需要添加列?
void _onCreate(Database db, int version) async {
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
要从旧版本更新您的数据库,您应该将 version
更改为 2
。
您应该像下面这样更改 onCreate
和 onUpdate
。
// This is called for new users who have no old db
void _onCreate(Database db, int version) async {
// if `AssetAssemblyTable` has a new column in version 2, add the column here.
await db.execute(
"""CREATE TABLE AssetAssemblyTable(e INTEGER, a INTEGER, c INTEGER)""");
)
await db.execute("CREATE TABLE NewTable...") // create new Table
}
// This is called for existing users who have old db(version 1)
void _onUpgrade(Database db, int oldVersion, int newVersion)async{
// In this case, oldVersion is 1, newVersion is 2
if (oldVersion == 1) {
await db.execute("ALTER TABLE AssetAssemblyTable...") // add new column to existing table.
await db.execute("CREATE TABLE NewTable...") // create new Table
}
}
更多示例如下
https://github.com/tekartik/sqflite/blob/master/sqflite/doc/migration_example.md