【问题标题】:How to store only new value to sqflite data table in (Flutter)如何在(Flutter)中仅将新值存储到 sqflite 数据表中
【发布时间】:2020-06-21 17:04:40
【问题描述】:

我已将电话列表存储到数据表中。我只想将新的通话清单数据存储到此数据表中。这意味着,只会保存新数据而跳过现有数据。 请举例说明。 这是我的代码:

这是数据库助手 database_helper.dart

import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

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 columnNumber = 'number';
  static final columnType = 'type';
  static final columnDate = 'date';
  static final columnDuration = 'duration';

  // 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 getExternalStorageDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    await deleteDatabase(path);
    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,
            $columnNumber INTEGER,
            $columnType TEXT,
            $columnDate DATETIME,
            $columnDuration INTEGER
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row, {ConflictAlgorithm conflictAlgorithm = ConflictAlgorithm.replace}) async {
    Database db = await instance.database;
    return await db.insert(table, row, conflictAlgorithm: conflictAlgorithm);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(
        await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }
  
  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }
}

这是主文件。我在这里只添加了数据库插入方法。 home.dart

...
Future callLogDB() async {
    Iterable<CallLogEntry> cLog = await CallLog.get();
    final dbHelper = DatabaseHelper.instance;

    cLog.forEach((log) async {
      // row to insert
      Map<String, dynamic> row = {
        DatabaseHelper.columnName: '${log.name}',
        DatabaseHelper.columnNumber: '${log.number}',
        DatabaseHelper.columnType: '${log.callType}',
        DatabaseHelper.columnDate:
            '${DateTime.fromMillisecondsSinceEpoch(log.timestamp)}',
        DatabaseHelper.columnDuration: '${log.duration}'
      };
      await dbHelper.insert(row, conflictAlgorithm: ConflictAlgorithm.replace);
      print('CallLog:: $row');
    });
    return cLog;
  }
...

我的代码有什么问题?

【问题讨论】:

    标签: flutter dart sqflite


    【解决方案1】:

    有几种方法可以做到这一点,我将提供的方法不是最好或最好的,但希望他们能有所帮助

    1) 只需将所有数据写入表格

    您可以将所有数据插入到表中,将 ConflictAlgorithm 设置为 replaceignore

    db.insert(table, data, conflictAlgorithm: ConflictAlgorithm.replace);
    

    这将替换/忽略相同的条目

    2) 查询、比较、替换

    这是一个不太“优雅”的解决方案,您可以先从表中查询所有数据

    db.query(table, columns: availableColumns, where: 'columnToQueryBy = ?', whereArgs: [neededValue]);
    

    然后与你拥有的数据进行比较

    然后如上使用db.insert()

    我认为在您的情况下,第一个选项更适合,this 示例几乎涵盖了可能对您有所帮助的大部分内容

    希望对你有帮助!

    【讨论】:

    • 我使用了你的第一个建议。但它仍然增加了旧值。这是我的数据库助手代码:Future&lt;int&gt; insert(Map&lt;String, dynamic&gt; row, {ConflictAlgorithm conflictAlgorithm}) async { Database db = await instance.database; return await db.insert(table, row, conflictAlgorithm: ConflictAlgorithm.ignore); }.,这是我的方法的一部分:dbHelper.insert(row, conflictAlgorithm: ConflictAlgorithm.ignore);
    • @SantoShakil 旧值在运行之间是否发生了变化?因为为了忽略冲突,条目必须完全相同
    • 我同时使用了忽略和替换,但之前插入的值仍然保持不变,并且所有值都存储在之前插入的行之后。
    • @SantoShakil 嗯,很奇怪,您能否将数据类型添加到您的帖子中?我对您提供的地图特别感兴趣
    • @SantoShakil 所以当你调用 cLog.forEach 时,columnDate 会更新吗?看来这可能是问题所在,如果为每个条目重写甚至一列,它不会被视为冲突
    【解决方案2】:

    如何从 Sqflite 读取数据并在数据表中显示?

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 2019-06-03
    • 2020-01-11
    • 2022-10-13
    • 2019-08-16
    • 2020-03-07
    相关资源
    最近更新 更多