如何使用 SQFlite 插件将数据插入 Flutter 中的数据库?
那里有许多解决问题的问题,但我找不到可以添加规范答案的问题。我的答案如下。
打开pubspec.yaml
并在依赖项部分添加以下行:
sqflite: ^1.0.0
path_provider: ^0.4.1
这当然sqflite
是SQFlite插件,path_provider
它将帮助我们获取 Android 和 iPhone 上的用户目录。
我在单例类中保留对数据库的全局引用。这将防止并发问题和数据泄漏(这是我听到的,但如果我错了请告诉我)。您还可以在此处添加辅助方法(如插入)以访问数据库。
创建一个名为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
该类。sqflite
Map<String, dynamic>
将列名映射到每行中的数据。id
. SQLite 自动为我们增加它。SQFlite 还支持进行原始插入。这意味着您可以使用 SQL 字符串。让我们再次使用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]
问号占位符被填写(?, ?)
。表名和列名使用插值更安全,所以我们最终可以这样做:
String name = 'Bob';
int age = 23;
db.rawInsert(
'INSERT INTO ${DatabaseHelper.table}'
'(${DatabaseHelper.columnName}, ${DatabaseHelper.columnAge}) '
'VALUES(?, ?)', [name, age]);
为了您的复制和粘贴方便,这里是布局代码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));
}
}
进入 pubspec.yaml
添加
dependency:
sqflite: any,
path_provider: any,
intl: ^0.15.7