如何在 Flutter 中从 txt 文件运行 sqlite INSERT INTO 查询?

问题描述 投票:0回答:1

我有一个 txt 文件,其中包含 sql INSERT INTO 查询和值。我想使用 sqlite 插件在 Dart/Flutter 中同时运行它们。这可能吗?

INSERT INTO article (id, name) VALUES (1, 'Banana') ; INSERT INTO article (id, name) VALUES (2, 'Orange') ; INSERT INTO article (id, name) VALUES (3, 'Apple') ;

我尝试的所有方法都不起作用

flutter sqlite dart insert txt
1个回答
0
投票

tl;博士

这是一个示例,演示了一个包含许多插入查询的文件,就像您在问题中提到的那样实际上它包含相同的插入查询

这是我在文件(inserts.txt)中放入的内容,完全在一行中:

插入文章(id,名称)VALUES(1,'香蕉');插入 文章(id,名称)VALUES(2,'橙色');插入文章(id, 名称)值(3,“苹果”);

文件的读取方式如下:

该函数的结果只是一个表示文件内容的字符串,或者

null
(如果文件不存在):

Future<String?> getInsertQuery({required String fileName}) async {
  File file = File(fileName);
  if (await file.exists()) {
    RandomAccessFile accessFile = await file.open();
    var list = utf8.decode(await accessFile.read(file.lengthSync()));
    return list;
  }

读取该文件后,您需要从所有这些指令中提取值:

List<String> getValues({required String allQueries}) {
  bool foundValue = false;
  String currentValue = "";
  List<String> valuesList = [];

  for (int i = 1; i < allQueries.length - 1; i++) {
    if (allQueries.codeUnitAt(i).compareTo('('.codeUnitAt(0)) == 0 &&
            allQueries.codeUnitAt(i + 1).compareTo('i'.codeUnitAt(0)) != 0 ||
        i == allQueries.length - 2) {
      foundValue = true;
      if (currentValue.isNotEmpty) {
        valuesList.add(currentValue);
      }
      currentValue = "";
    }
    if (allQueries.codeUnitAt(i - 1).compareTo(')'.codeUnitAt(0)) == 0) {
      foundValue = false;
    }
    if (foundValue) {
      currentValue += allQueries.substring(i, i + 1);
    }
  }
  return valuesList;
}
  return null;
}

上面的函数只是返回一个包含所有值的列表,例如:

[(1, 'Banana') ,(2, 'Orange') ,(3, 'Apple')]

最难的部分已经完成,现在构建插入查询:

void writeQuery({required List<String> values}) {
  String query = 'INSERT INTO article (id, name) VALUES ';
  for (int i = 0; i < values.length; i++) {
    query += '${values[i]} ${i == values.length - 1 ? ';' : ','}';
  }
  print(query);
}

它获取值列表并以字符串表示形式返回查询:

输出:

 INSERT INTO article (id, name) VALUES (1, 'Banana') ,(2, 'Orange') ,(3, 'Apple') ;

当然,这是主要功能:

void main() async {
  final String? queries = await getInsertQuery(
      fileName:
          'give it the file path');

  if (queries == null) {
    print('No Data found or file not exist');
  } else {
    writeQuery(values: getValues(allQueries: queries));
  }
}

毕竟,您需要获取累积查询并将其传递给数据库管理器以插入它们:

  INSERT INTO article (id, name) VALUES (1, 'Banana') ,(2, 'Orange') ,(3, 'Apple') ;
© www.soinside.com 2019 - 2024. All rights reserved.