gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:32:43 25 4
gpt4 key购买 nike

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

  • id大主键
  • display_name TEXT NOT NULL,
  • 电子邮件TEXT NOT NULL
  • phone_number TEXT

  • 我想从 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": "foo@gmail.com"
    };
    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": "foo@gmail.com"
    };
    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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com