如何使用SQFlite插件将数据插入Flutter中的数据库?
有很多问题解决问题,但我找不到能为之添加规范答案的问题。我的答案如下。
打开pubspec.yaml并在依赖项部分中添加以下行:
pubspec.yaml
sqflite: ^1.0.0 path_provider: ^0.4.1
该sqflite是SQFlite当然插件和path_provider将帮助我们在Android和iPhone用户目录。
sqflite
path_provider
我在单例类中保持对数据库的全局引用。这将防止并发问题和数据泄漏(这是我所听到的,但请告诉我是否错误)。您也可以在此处添加用于访问数据库的辅助方法(如insert)。
创建一个名为 database_helper.dart 的新文件,并粘贴以下代码:
import 'dart:io' show Directory; import 'package:path/path.dart' show join; import 'package:sqflite/sqflite.dart'; import 'package:path_provider/path_provider.dart' show getApplicationDocumentsDirectory; class DatabaseHelper { static final _databaseName = "MyDatabase.db"; static final _databaseVersion = 1; static final table = 'my_table'; static final columnId = '_id'; static final columnName = 'name'; static final columnAge = 'age'; // make this a singleton class DatabaseHelper._privateConstructor(); static final DatabaseHelper instance = DatabaseHelper._privateConstructor(); // only have a single app-wide reference to the database static Database _database; Future<Database> get database async { if (_database != null) return _database; // lazily instantiate the db the first time it is accessed _database = await _initDatabase(); return _database; } // this opens the database (and creates it if it doesn't exist) _initDatabase() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, _databaseName); return await openDatabase(path, version: _databaseVersion, onCreate: _onCreate); } // SQL code to create the database table Future _onCreate(Database db, int version) async { await db.execute(''' CREATE TABLE $table ( $columnId INTEGER PRIMARY KEY, $columnName TEXT NOT NULL, $columnAge INTEGER NOT NULL ) '''); } }
我们将使用异步方法进行插入:
_insert() async { // get a reference to the database // because this is an expensive operation we use async and await Database db = await DatabaseHelper.instance.database; // row to insert Map<String, dynamic> row = { DatabaseHelper.columnName : 'Bob', DatabaseHelper.columnAge : 23 }; // do the insert and get the id of the inserted row int id = await db.insert(DatabaseHelper.table, row); // show the results: print all rows in the db print(await db.query(DatabaseHelper.table)); }
笔记
DatabaseHelper
Map<String, dynamic>
id
SQFlite还支持原始插入。这意味着您可以使用SQL字符串。让我们再次使用插入同一行rawInsert()。
rawInsert()
db.rawInsert('INSERT INTO my_table(name, age) VALUES("Bob", 23)');
当然,我们不想将这些值硬编码到SQL字符串中,但是我们也不想使用这样的互斥:
String name = 'Bob'; int age = 23; db.rawInsert('INSERT INTO my_table(name, age) VALUES($name, $age)'); // Dangerous!
这将使我们容易受到SQL注入攻击的攻击。相反,我们可以这样使用数据绑定:
db.rawInsert('INSERT INTO my_table(name, age) VALUES(?, ?)', [name, age]);
该[name, age]是在问号占位符填充(?, ?)。表名和列名更安全地用于交互,因此我们最终可以这样做:
[name, age]
(?, ?)
String name = 'Bob'; int age = 23; db.rawInsert( 'INSERT INTO ${DatabaseHelper.table}' '(${DatabaseHelper.columnName}, ${DatabaseHelper.columnAge}) ' 'VALUES(?, ?)', [name, age]);
为了方便您复制和粘贴,以下是以下代码的布局代码main.dart:
main.dart
import 'package:flutter/material.dart'; import 'package:flutter_db_operations/database_helper.dart'; import 'package:sqflite/sqflite.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'SQFlite Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('sqflite'), ), body: RaisedButton( child: Text('insert', style: TextStyle(fontSize: 20),), onPressed: () {_insert();}, ), ); } _insert() async { // get a reference to the database // because this is an expensive operation we use async and await Database db = await DatabaseHelper.instance.database; // row to insert Map<String, dynamic> row = { DatabaseHelper.columnName : 'Bob', DatabaseHelper.columnAge : 23 }; // do the insert and get the id of the inserted row int id = await db.insert(DatabaseHelper.table, row); // raw insert // // String name = 'Bob'; // int age = 23; // int id = await db.rawInsert( // 'INSERT INTO ${DatabaseHelper.table}' // '(${DatabaseHelper.columnName}, ${DatabaseHelper.columnAge}) ' // 'VALUES(?, ?)', [name, age]); print(await db.query(DatabaseHelper.table)); } }