Мне нужно добавить новое имя столбца id INTEGER AUTOINCREMENT
и новую таблицу для текущей базы данных для моей существующей таблицы. Как использовать «обновление»? Нужно ли менять номер версии?
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
Вам не нужно что-то делать с переменной version
в _onCreate
. Я предполагаю, что это для отладки.
Сообщение об ошибке: Unhandled Exception: DatabaseException(table UsernameTable has no column named rememberMe (Sqlite code 1): , while compiling: INSERT OR REPLACE INTO UsernameTable (username, rememberMe) VALUES (?, ?), (OS error - 2:No such file or directory)) sql 'INSERT OR REPLACE INTO UsernameTable (username, rememberMe) VALUES (?, ?)' args [term@melfs, 1]}
initDb() async { io.Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "HelperDatabase.db"); var theDb = await openDatabase(path, version: 4, onCreate: _onCreate, onUpgrade: _onUpgrade); return theDb; }
void _onUpgrade(Database db, int oldVersion, int newVersion)async{ if (oldVersion != 5){ await db.execute("ALTER TABLE UsernameTable ADD COLUMN rememberMe INTEGER DEFAULT 0"); } }
можно ответить на этот вопрос? stackoverflow.com/q/56323951/8822337
нужно ли увеличивать номер версии метода
_onCreate()
при изменении таблицы?