如何在sqflite
中快速插入多个记录?标准的快速方法是:
await database.insert(table, object.toMap())
但是我不认为插入记录与循环一对一是一个好主意。 或者我可以在交易中插入所有列表?
答案 0 :(得分:1)
在这种情况下,您可以使用批处理。
batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();
大批量,您可以使用await batch.commit(noResult: true);
答案 1 :(得分:1)
正如我在评论中提到的,您可以使用Batch
。这是示例。
Batch batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
现在,如果您要查找结果(这会花费一些内存),请使用
results = await batch.commit();
如果您正在寻找快速的性能,只需忽略结果并使用
await batch.commit(noResult: true);
答案 2 :(得分:1)
如果您有要插入的对象列表,则可以这样进行操作(这不是很干净的代码,但是可以使用):
insertClients(List<Client> clients) async {
final db = await database;
var buffer = new StringBuffer();
clients.forEach((c) {
if (buffer.isNotEmpty) {
buffer.write(",\n");
}
buffer.write("('");
buffer.write(c.firstName);
buffer.write("', '");
buffer.write(c.lastName);
buffer.write("', '");
buffer.write(c.address);
buffer.write("')");
});
var raw =
await db.rawInsert("INSERT Into Clients (firstName,lastName,address)"
" VALUES ${buffer.toString()}");
return raw;
}
我正在使用SQLite中的以下语句:
INSERT INTO 'tablename' ('column1', 'column2') VALUES
('data1', 'data2'),
('data1', 'data2'),
('data1', 'data2');
答案 3 :(得分:0)
我看到了使用数据库事务的可能性,这与Android非常相似。 我发现最好使用它们,在这里我展示了一个示例代码,如果它对某人有用的话。 在我的示例中显示了try-catches,但是可以使用Future函数回调来获得更简洁的代码:
Future<List<dynamic>> insertAll(String table, List<dynamic> objects) async {
List<dynamic> listRes = new List();
var res;
try {
await DbHelper().database.transaction((db) async {
objects.forEach((obj) async {
try {
var iRes = await db.insert(table, obj.toMap());
listRes.add(iRes);
} catch (ex) {
DbHelper().databaseLog(CON_INSERT_MULTIPLE, "Error!", ex);
}
});
});
DbHelper().databaseLog(CON_INSERT_MULTIPLE, table, listRes);
res = listRes;
} catch (er) {
res = OutComeCallClient.ERROR;
DbHelper().databaseLog(CON_INSERT_MULTIPLE, "Error!", er);
}
return res;
}
答案 4 :(得分:0)
这是我的代码,也许可以帮忙;) 感谢MihaiV。
insertOrUpdateAll(List<Map<String, dynamic>> ticks) async {
if (ticks.length == 0) return null;
final columns = ticks.first.keys.join(",");
var valuesBuffer = new StringBuffer();
ticks.forEach((task) {
if (valuesBuffer.isNotEmpty) valuesBuffer.write(",\n");
valuesBuffer.write("(");
int ix = 0;
task.forEach((key, value) {
if (ix++ != 0) valuesBuffer.write(',');
final isString =
columnsInfo.where((c) => c.name == key).first.type == RowType.text;
if (isString) valuesBuffer.write("'$value'");
valuesBuffer.write(value);
});
valuesBuffer.write(")");
});
return await db.rawInsert("INSERT Into Clients ($columns)"
" VALUES ${valuesBuffer.toString()}");
}
答案 5 :(得分:0)
Model
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
final String tableName = "todom";
final String Column_id = "id";
final String Column_name = "name";
class TaskModel{
final String name;
int id;
TaskModel({this.name, this.id});
Map<String, dynamic> toMap(){
return {
Column_name : this.name
};
}
}
class TodoHelper{
Database db;
TodoHelper(){
initDatabase();
}
Future<void> initDatabase() async{
db = await openDatabase(
join(await getDatabasesPath(), "databse.db"),
onCreate: (db, version){
return db.execute("CREATE TABLE $tableName($Column_id INTEGER PRIMARY KEY AUTOINCREMENT, $Column_name TEXT)");
},
version: 1
);
}
Future<void> insertTask(TaskModel task) async{
try{
db.insert(tableName, task.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
}catch(_){
print(_);
}
}
Future<List<TaskModel>> getAllTask () async{
final List<Map<String, dynamic>> tasks = await db.query(tableName);
return List.generate(tasks.length, (i){
return TaskModel(name: tasks[i][Column_name], id: tasks[i][Column_id]);
});
}
}
main.dart
import 'package:flutter/material.dart';
import 'TaskModel.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final textController = TextEditingController();
List<TaskModel> tasks = [];
TaskModel currentTask;
@override
Widget build(BuildContext context) {
final TodoHelper _todoHelper = TodoHelper();
return Scaffold(
body: Container(
padding:EdgeInsets.all(32),
child: Column(
children: <Widget>[
TextField(
controller: textController,
),
FlatButton(
child: Text("Insert"),
onPressed: (){
currentTask = TaskModel(name: textController.text);
_todoHelper.insertTask(currentTask);
},
color: Colors.blue,
textColor: Colors.white,
),
FlatButton(
child: Text("Show All Task"),
onPressed: () async{
List<TaskModel> list = await _todoHelper.getAllTask();
setState(() {
tasks = list;
});
},
color: Colors.red,
textColor: Colors.white,
),
Expanded(
child: ListView.separated(
itemBuilder: (context, index){
return ListTile(
leading: Text("${tasks[index].id}"),
title: Text("${tasks[index].name}"),
);
},
separatorBuilder: (context, index) => Divider(),
itemCount: tasks.length,
),
)
],
),
),
);
}
}
答案 6 :(得分:0)
您可以尝试使用 rawInsert
Database db = await instance.database;
String sql = '''
INSERT INTO p_tasklistproviderobjective (
idticket,
objective
) VALUES (?, ?)
''';
//you can get this data from json object /API
List<Map> data = [
{"idticket": 5, "objective": "dono"},
{"idticket": 6, "objective": "dono2"},
{"idticket": 7, "objective": "dono3"},
{"idticket": 8, "objective": "dono4"},
];
//and then loop your data here
data.forEach((element) async {
await db.rawInsert(sql, [element['idticket'], element['objective']]);
});