Unsupported versions: 7.0 / 6.5 / 6.4
This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the current version, or one of the other supported versions listed above instead.

Chapter 53. libpq

libpq is the C application programmer's interface to Postgres. libpq is a set of library routines that allow client programs to pass queries to the Postgres backend server and to receive the results of these queries. libpq is also the underlying engine for several other Postgres application interfaces, including libpq++ (C++), libpgtcl (Tcl), perl5, and ecpg. So some aspects of libpq's behavior will be important to you if you use one of those packages. Three short programs are included at the end of this section to show how to write programs that use libpq. There are several complete examples of libpq applications in the following directories:


Frontend programs which use libpq must include the header file libpq-fe.h and must link with the libpq library.

Database Connection Functions

The following routines deal with making a connection to a Postgres backend server. The application program can have several backend connections open at one time. (One reason to do that is to access more than one database.) Each connection is represented by a PGconn object which is obtained from PQconnectdb() or PQsetdbLogin(). NOTE that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate the PGconn object. The PQstatus function should be called to check whether a connection was successfully made before queries are sent via the connection object.

  • PQsetdbLogin Makes a new connection to a backend.

    PGconn *PQsetdbLogin(const char *pghost,
                    const char *pgport,
                    const char *pgoptions,
                    const char *pgtty,
                    const char *dbName,
                    const char *login,
                    const char *pwd)
    If any argument is NULL, then the corresponding environment variable (see "Environment Variables" section) is checked. If the environment variable is also not set, then hardwired defaults are used. The return value is a pointer to an abstract struct representing the connection to the backend.
  • PQsetdb Makes a new connection to a backend.

    PGconn *PQsetdb(char *pghost,
                    char *pgport,
                    char *pgoptions,
                    char *pgtty,
                    char *dbName)
    This is a macro that calls PQsetdbLogin() with null pointers for the login and pwd parameters. It is provided primarily for backward compatibility with old programs.
  • PQconnectdb Makes a new connection to a backend.

    PGconn *PQconnectdb(const char *conninfo)
    This routine opens a new database connection using parameters taken from a string. Unlike PQsetdbLogin(), the parameter set can be extended without changing the function signature, so use of this routine is encouraged for new application programming. The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. (To write a null value or a value containing spaces, surround it with single quotes, eg, keyword = 'a value'. Single quotes within the value must be written as \'. Spaces around the equal sign are optional.) The currently recognized parameter keywords are:
    • host -- host to connect to. If a non-zero-length string is specified, TCP/IP communication is used. Without a host name, libpq will connect using a local Unix domain socket.

    • port -- port number to connect to at the server host, or socket filename extension for Unix-domain connections.

    • dbname -- database name.

    • user -- user name for authentication.

    • password -- password used if the backend demands password authentication.

    • authtype -- authorization type. (No longer used, since the backend now chooses how to authenticate users. libpq still accepts and ignores this keyword for backward compatibility.)

    • options -- trace/debug options to send to backend.

    • tty -- file or tty for optional debug output from backend.

    Like PQsetdbLogin, PQconnectdb uses environment variables or built-in default values for unspecified options.

  • PQconndefaults Returns the default connection options.

    PQconninfoOption *PQconndefaults(void)
    struct PQconninfoOption
                    char   *keyword;   /* The keyword of the option */
                    char   *envvar;    /* Fallback environment variable name */
                    char   *compiled;  /* Fallback compiled in default value */
                    char   *val;       /* Option's value */
                    char   *label;     /* Label for field in connect dialog */
                    char   *dispchar;  /* Character to display for this field
                                          in a connect dialog. Values are:
                                          ""        Display entered value as is
                                          "*"       Password field - hide value
                                          "D"       Debug options - don't
                                          create a field by default */
                    int     dispsize;  /* Field size in characters for dialog */
    Returns the address of the connection options structure. This may be used to determine all possible PQconnectdb options and their current default values. The return value points to an array of PQconninfoOption structs, which ends with an entry having a NULL keyword pointer. Note that the default values ("val" fields) will depend on environment variables and other context. Callers must treat the connection options data as read-only.
  • PQfinish Close the connection to the backend. Also frees memory used by the PGconn object.

    void PQfinish(PGconn *conn)
    Note that even if the backend connection attempt fails (as indicated by PQstatus), the application should call PQfinish to free the memory used by the PGconn object. The PGconn pointer should not be used after PQfinish has been called.
  • PQreset Reset the communication port with the backend.

    void PQreset(PGconn *conn)
    This function will close the connection to the backend and attempt to reestablish a new connection to the same postmaster, using all the same parameters previously used. This may be useful for error recovery if a working connection is lost.

libpq application programmers should be careful to maintain the PGconn abstraction. Use the accessor functions below to get at the contents of PGconn. Avoid directly referencing the fields of the PGconn structure because they are subject to change in the future. (Beginning in Postgres release 6.4, the definition of struct PGconn is not even provided in libpq-fe.h. If you have old code that accesses PGconn fields directly, you can keep using it by including libpq-int.h too, but you are encouraged to fix the code soon.)

  • PQdb Returns the database name of the connection.

    char *PQdb(PGconn *conn)
    PQdb and the next several functions return the values established at connection. These values are fixed for the life of the PGconn object.
  • PQuser Returns the user name of the connection.

    char *PQuser(PGconn *conn)
  • PQpass Returns the password of the connection.

    char *PQpass(PGconn *conn)
  • PQhost Returns the server host name of the connection.

    char *PQhost(PGconn *conn)
  • PQport Returns the port of the connection.

    char *PQport(PGconn *conn)
  • PQtty Returns the debug tty of the connection.

    char *PQtty(PGconn *conn)
  • PQoptions Returns the backend options used in the connection.

    char *PQoptions(PGconn *conn)
  • PQstatus Returns the status of the connection. The status can be CONNECTION_OK or CONNECTION_BAD.

    ConnStatusType *PQstatus(PGconn *conn)

    A failed connection attempt is signaled by status CONNECTION_BAD. Ordinarily, an OK status will remain so until PQfinish, but a communications failure might result in the status changing to CONNECTION_BAD prematurely. In that case the application could try to recover by calling PQreset.

  • PQerrorMessage Returns the error message most recently generated by an operation on the connection.

    char *PQerrorMessage(PGconn* conn);

    Nearly all libpq functions will set PQerrorMessage if they fail. Note that by libpq convention, a non-empty PQerrorMessage will include a trailing newline.

  • PQbackendPID Returns the process ID of the backend server handling this connection.

    int PQbackendPID(PGconn *conn);
    The backend PID is useful for debugging purposes and for comparison to NOTIFY messages (which include the PID of the notifying backend). Note that the PID belongs to a process executing on the database server host, not the local host!