postgresql - 使用 dart 将数据插入 Postgres 数据库

标签 postgresql dart crud

我有一个 postgres 数据库,其中包含一个名为“users”的表。该表有四个字段:

  • ID BIGSERIAL 主键
  • 显示名称文本不为空,
  • 电子邮件文本不为空
  • 电话号码文本

我想通过 dart 代码向其中添加数据。 我的尝试如下:

import "dart:io";
import "package:postgres/postgres.dart";
void main() async{
  var connection = PostgreSQLConnection(
        "localhost", 5432, "test",
        username: "something", password: "notTellingYou");
    try {
      await connection.open();
    } catch (e) {
      print(e);
    }

  Map<String, dynamic> data = {
    "display_name": "foo",
    "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5a3aaaa85a2a8a4aca9eba6aaa8" rel="noreferrer noopener nofollow">[email protected]</a>"
  };
  await setData(connection, "users", data);
  
}

Future<void> setData(PostgreSQLConnection connection, String table, Map<String, dynamic> data) async {
  await connection.query("""
    INSERT INTO $table(${data.keys})
    VALUES ${data.values};
  """);
}

问题是我遇到了异常

(PostgreSQLSeverity.error 42601: syntax error at or near "display_name" )

最佳答案

尝试使用变量替换:

import "dart:io";
import "package:postgres/postgres.dart";

Future<void> main() async {
  final connection = PostgreSQLConnection("localhost", 5432, "test",
      username: "something", password: "notTellingYou");
  await connection.open();

  final data = <String, dynamic>{
    "display_name": "foo",
    "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="492f2626092e24282025672a2624" rel="noreferrer noopener nofollow">[email protected]</a>"
  };
  await setData(connection, "users", data);
  await connection.close();
}

Future<void> setData(PostgreSQLConnection connection, String table,
    Map<String, dynamic> data) async {
  await connection.execute(
      'INSERT INTO $table (${data.keys.join(', ')}) VALUES (${data.keys.map((k) => '@$k').join(', ')})',
      substitutionValues: data);
}

生成的文本将是:“INSERT INTO users (display_name, email) VALUES (@display_name, @email)” 和每个变量(以 @ 开头)将自动替换为 map 中每个键的值。

这还将确保您的值中特殊字符的正确转义。

关于postgresql - 使用 dart 将数据插入 Postgres 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62950986/

相关文章:

flutter - 如何在 Flutter 的导航器中使用 WillPopScope?

flutter - 在 Flutter 中根据屏幕大小重新排列 UI 元素

java - 玩! JPA : Enforce not to create Entity on load

php - 最简单的 PHP 表单验证库?

linux - 需要帮助更改 CentOS 7 上的 postgresql 端口

ruby-on-rails - Postgres 问题 - Google Container Engine 上的 Ruby on Rails (Postgres)

mysql - 大表的 PostgreSQL 到 MySQL 转换

postgresql - 如何在 postgres UTF8 客户端编码中获取 "€"(u+20AC) 字符?

flutter - ListView.builder按需创建窗口小部件是什么意思?

java - 避免在聚合子模型上使用持久层