Client 1—Connecting to the Server

To interact with a PostgreSQL server using Python's DB-API, you must first import the pgdb module. This module defines a few exception classes (we'll talk about exceptions a little later), two classes (pgdbCnx and pgdbCursor), and a single module function.

The pgdb.connect() function returns a connection object (an instance of class pgdbCnx). This function actually comes in two flavors:

pgdb.connect( dsn )
pgdb.connect( dsn      = dsn, 
              user     = user, 
              password = password, 
              host     = host, 
              database = dbname )

In the first flavor, the dsn is expected to be a string of the form:

host:database:user:password:opt:tty

The rules for composing a valid dsn are a bit complex. In the simplest case, you can specify all connection ...

Get PostgreSQL, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.