简体   繁体   English

如何在 Flutter 中使用 SQFlite 进行数据库表更新

[英]How to do a database table update with SQFlite in Flutter

How do you update data in a table row in Flutter using the SQFlite plugin?如何使用 SQFlite 插件更新 Flutter 中表行中的数据?

There are a number of problem solving questions out there (see this and this ) but none that I could find to add a canonical answer to.那里有许多解决问题的问题(请参阅thisthis ),但我找不到可以添加规范答案的问题。 My answer is below.我的答案如下。

Add the dependencies添加依赖项

Open pubspec.yaml and in the dependency section add the following lines:打开pubspec.yaml并在依赖项部分添加以下行:

sqflite: ^1.0.0
path_provider: ^0.4.1

The sqflite is the SQFlite plugin of course and the path_provider will help us get the user directory on Android and iPhone. sqflite当然是SQFlite插件, path_provider将帮助我们在 Android 和 iPhone 上获取用户目录。

Make a database helper class制作一个数据库助手类

I'm keeping a global reference to the database in a singleton class.我在单例类中保留对数据库的全局引用。 This will prevent concurrency issues and data leaks (that's what I hear, but tell me if I'm wrong).这将防止并发问题和数据泄漏(这是我听到的,但如果我错了,请告诉我)。 You can also add helper methods (like update) in here for accessing the database.您还可以在此处添加辅助方法(如更新)以访问数据库。

Create a new file called database_helper.dart and paste in the following code:创建一个名为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
          )
          ''');
  }
}

Update row更新行

First lets insert a row so that we have something to update:首先让我们插入一行,以便我们有一些东西要更新:

  _insert() async {
    Database db = await DatabaseHelper.instance.database;
    Map<String, dynamic> row = {
      DatabaseHelper.columnName : 'Bob',
      DatabaseHelper.columnAge  : 23
    };
    int id = await db.insert(DatabaseHelper.table, row);
    print(await db.query(DatabaseHelper.table));
  }

Then this is how to do the update:然后这是如何进行更新:

  _update() 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 update
    Map<String, dynamic> row = {
      DatabaseHelper.columnName : 'Mary',
      DatabaseHelper.columnAge  : 32
    };

    // We'll update the first row just as an example
    int id = 1;

    // do the update and get the number of affected rows
    int updateCount = await db.update(
        DatabaseHelper.table,
        row,
        where: '${DatabaseHelper.columnId} = ?',
        whereArgs: [id]);

    // show the results: print all rows in the db
    print(await db.query(DatabaseHelper.table));
  }

Notes笔记

  • You will have to import the DatabaseHelper class and sqflite if you are in another file (like main.dart).如果您在另一个文件(如 main.dart)中,则必须导入DatabaseHelper类和sqflite
  • The SQFlite plugin uses a Map<String, dynamic> to map the column names to the data in each row. SQFlite 插件使用Map<String, dynamic>将列名映射到每一行中的数据。

Raw update原始更新

SQFlite also supports doing a raw update. SQFlite 还支持进行原始更新。 This means that you can use a SQL string.这意味着您可以使用 SQL 字符串。 Lets update the same row again using rawUpdate() .让我们使用rawUpdate()再次更新同一行。

int updateCount = await db.rawUpdate('''
    UPDATE my_table 
    SET name = ?, age = ? 
    WHERE _id = ?
    ''', 
    ['Susan', 13, 1]);

The items in the brackets at the end are bound to the ?末尾括号中的项目绑定到? question marks in the SQL string. SQL 字符串中的问号。 You can use interpolation to fill in the table and column names but you shouldn't use interpolation for the values because of the danger of SQL injection attacks.您可以使用插值来填充表名和列名,但您不应该对值使用插值,因为存在 SQL 注入攻击的危险。

int updateCount = await db.rawUpdate('''
    UPDATE ${DatabaseHelper.table} 
    SET ${DatabaseHelper.columnName} = ?, ${DatabaseHelper.columnAge} = ? 
    WHERE ${DatabaseHelper.columnId} = ?
    ''',
    ['Susan', 13, 1]);

请试试这个

await db.update(TABLE_NAME, data, where: 'column = ?', whereArgs: [value]); 

Just use this function for SqlFlite Update in flutter只需在flutter中将此功能用于SqlFlite Update

  Future<int> update(TaskModel task, id) async {
return await db.update(tableName, task.toMap(),
    where: '$columnId = ?', whereArgs: [id]);}

*UPDATE SYNTEX, " update Test set name='$name',contact='$contact' where id=${widget.map!['id']}";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM