如何使用SQFlite插件将数据插入Flutter中的数据库?
这里有许多问题解决问题,但我找不到能为之添加规范答案的问题。我的答案在下面。
答案 0 :(得分:2)
打开pubspec.yaml
,然后在“依赖项”部分中添加以下行:
sqflite: ^1.0.0
path_provider: ^0.4.1
sqflite
当然是SQFlite插件,而path_provider
将帮助我们在Android和iPhone上获取用户目录。
我在单例类中保持对数据库的全局引用。这将防止并发问题和数据泄漏(这是我所听到的,但请告诉我是否错误)。您也可以在此处添加用于访问数据库的辅助方法(如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
类和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));
}
}
答案 1 :(得分:-1)
获取pubspec.yaml
添加
dependency:
sqflite: any,
path_provider: any,
intl: ^0.15.7