我在網上找到了一個顫振的 sqfl 示例,并試圖為我的個人專案修改它。
我需要一個資料庫中的多個表,因此我希望能夠通過在運行時提供 tableName 引數來創建不同的表。
當我嘗試在 '_onCreate' 方法中添加 tableName 作為引數來創建表時,我收到一個錯誤,警告我“引數型別'Future Function(Database, int, String)' 不能分配給引數型別'未來或函式(資料庫,int)?'。
// this opens the database (and creates it if it doesn't exist)
_initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion, onCreate: _onCreate);
}
// SQL code to create the database table
Future _onCreate(Database db, int version, String tableName) async {
await db.execute('''
CREATE TABLE $tableName (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnName TEXT NOT NULL,
$columnMiles INTEGER NOT NULL
)
''');
}
uj5u.com熱心網友回復:
您可以單獨創建查詢,然后同時執行所有查詢,如下所示
queryForFirstTable = 'CREATE TABLE TABLENAME(your properties here)';
queryForSecondTable= 'CREATE TABLE ANOTHERTABLENAME(your properties here)';
await openDatabase(
join(await getDatabasesPath(), dbName),
version: 1, onCreate: (Database db, int version) async {
await db.execute(queryForFirstTable);
await db.execute(queryForSecondTable);
});
希望通過這樣做,您可以輕松創建多個表。
uj5u.com熱心網友回復:
void _createDb(Database db, int newVersion) async {
await db.execute('''
create table $carTable (
$columnCarId integer primary key autoincrement,
$columnCarTitle text not null
)''');
await db.execute('''
create table $userTable(
$userId integer primary key autoincrement,
$name text not null
)''');
}
一次創建多個表。
uj5u.com熱心網友回復:
onCreate 的函式只能帶兩個引數 Function(Database, int)?所以它不允許再傳遞一個引數。所以我決定通過另一個函式將我的變數傳遞給 sql 查詢字串;
Future _onCreateTable(
Database db,
int version,
) async {
await db.execute(sqlTableCreation('cars_table'));
}
String sqlTableCreation(String tableName) {
String result = "''' CREATE TABLE $tableName ($columnId INTEGER PRIMARY KEY AUTOINCREMENT,$columnName TEXT NOT NULL,$columnMiles INTEGER NOT NULL)'''";
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/469328.html
