title: libpq how to pass bulk data
body: <p>I'm trying to pass multiple rows to a test table and I'm having trouble understanding how exactly it's done in libpq.</p>
  
  <p>I've found commands for copying data that I believe are needed, but there aren't any examples as to how to use them.
  <a href="https://www.postgresql.org/docs/8.3/static/libpq-copy.html" rel="nofollow noreferrer">https://www.postgresql.org/docs/8.3/static/libpq-copy.html</a></p>
  
  <p>Here's the code I've came up with, but I'm getting segmentation faults at the PQputCopyEnd function. I'm pretty lost here so any help would be great.</p>
  
  <pre><code>/*
   * testlibpq.c
   *
   *      Test the C version of libpq, the PostgreSQL frontend library.
   */
  #include &lt;stdio.h&gt;
  #include &lt;string&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;postgresql/libpq-fe.h&gt;
  
  static void exit_nicely(PGconn *conn)
  {
      PQfinish(conn);
      exit(1);
  }
  
  int main(int argc, char **argv)
  {
      const char *conninfo, *errmsg;
      PGconn     *conn;
      PGresult   *res;
  
      //std::string buffer = "key1\tcol11\tcol12\nley2\tcol21\tcol22";
      std::string buffer = "key1\tcol11\tcol12";
  
  
      if (argc &gt; 1)
          conninfo = argv[1];
      else
          conninfo = "dbname=postgres host=129.24.26.136 user=postgres password=postgresUNM";
  
      /* Make a connection to the database */
      conn = PQconnectdb(conninfo);
  
      /* Check to see that the backend connection was successfully made */
      if (PQstatus(conn) != CONNECTION_OK)
      {
          fprintf(stderr, "Connection to database failed: %s",
                  PQerrorMessage(conn));
          exit_nicely(conn);
      }
  
      //do stuff here
      res = PQexec(conn, "COPY cplusplustest from STDIN");
      int a = PQputCopyData(conn, buffer.c_str(), buffer.length());
  
      res = PQexec(conn, "COMMIT");
  
      int b = PQputCopyEnd(conn, errmsg);
  
      if (errmsg == NULL)
      {
          printf("worked.\n");
      }
  
      /* close the connection to the database and cleanup */
      PQfinish(conn);
  
      return 0;
  }
  </code></pre>