【问题标题】:Insert Binary Large Object (BLOB) in PostgreSQL using libpq from remote machine使用远程机器的 libpq 在 PostgreSQL 中插入二进制大对象 (BLOB)
【发布时间】:2013-04-21 08:10:35
【问题描述】:

您能否举一个使用 libpq 从远程机器将二进制数据插入 PostgreSQL 数据库的示例。 我的第二个问题是:是否有任何其他 API 比使用 C++ 的 libpq 更有效。 谢谢

【问题讨论】:

    标签: c++ c database postgresql libpq


    【解决方案1】:

    PostgreSQL中有两种类型的blob——BYTEALarge Objects。我建议不要使用大对象,因为您无法将它们加入表格。

    对于 BYTEA,你会在 libpq 中使用类似的东西:

    PGresult* put_data_to_tablename(
      PGconn* conn,
      int32_t id,
      int data_size,
      const char* const data
    ) {
      PGresult* result;
      const uint32_t id_big_endian = htonl((uint32_t)id);
      const char* const paramValues[] = { &id_big_endian, data };
      const int nParams = sizeof(paramValues) / sizeof(paramValues[0]);
      const int paramLenghts[] = { sizeof(id_big_endian), data_size };
      const int paramFormats[] = { 1, 1 }; /* binary */
      const int resultFormat = 0; /* text */
    
      result = PQexecParams(
        conn,
        "insert into tablename (id, data) values ($1::integer, $2::bytea)",
        nParams,
        NULL, /* Types of parameters, unused as casts will define types */
        paramValues,
        paramLenghts,
        paramFormats,
        resultFormat
      );
      return result;
    }
    

    【讨论】:

      【解决方案2】:

      使用 libpqxx 是 C++ 方法,而 libpq 是 C API。

      下面是如何使用 pqxx 的完整示例:How to insert binary data into a PostgreSQL BYTEA column using the C++ libpqxx API?

      简而言之,使用 libpqxx 的相关 C++ 行如下所示:

      void * bin_data = ...; // obviously do what you need to get the binary data...
      size_t bin_size = ...; // ...and the size of the binary data
      pqxx::binarystring bin( bin_data, bin_size );
      pqxx::result r = work.prepared( "test" )( bin ).exec();
      work.commit();
      

      【讨论】:

      • 值得注意的是,libpqxx 存在老化问题,不,它不是网站上所说的“官方”postgresql c++ api。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2010-10-18
      • 2020-06-12
      • 2013-12-14
      相关资源
      最近更新 更多