Skip to content

Instantly share code, notes, and snippets.

@lpsmith
Created January 18, 2011 01:15
Show Gist options
  • Save lpsmith/783835 to your computer and use it in GitHub Desktop.
Save lpsmith/783835 to your computer and use it in GitHub Desktop.
Example of binary IO using libpq
// This is a demonstration of binary input into postgres using libpq. It
// is based on postgresql-9.0.2/src/test/examples/testlibpq3.c
//
// Create a table appropriate to this test in a database as follows:
//
// CREATE TABLE test (name BYTEA);
//
// See also http://article.gmane.org/gmane.comp.lang.haskell.cafe/85116
#ifdef WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <libpq-fe.h>
/* for ntohl/htonl */
#include <netinet/in.h>
#include <arpa/inet.h>
static void
exit_nicely(PGconn *conn)
{
PQfinish(conn);
exit(1);
}
int
main(int argc, char **argv)
{
const char *conninfo;
PGconn *conn;
PGresult *res;
const char *paramValues[1];
int paramLengths[1];
int paramFormats[1];
uint32_t binaryIntVal;
if (argc > 1)
conninfo = argv[1];
else
conninfo = "dbname=postgres";
/* 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);
}
/* Here is our out-of-line parameter value */
paramValues[0] = "\x41\x00\x41";
paramLengths[0] = 3;
paramFormats[0] = 1; /* parameters are passed in a binary format */
res = PQexecParams(conn,
"INSERT INTO test (name) VALUES ($1::bytea)",
1, /* one param */
NULL, /* let the backend deduce param type */
paramValues,
paramLengths,
paramFormats,
1); /* ask for binary results */
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "INSERT failed: %s\n", PQerrorMessage(conn));
PQclear(res);
exit_nicely(conn);
}
PQclear(res);
PQfinish(conn);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment