A psycopg2 wrapper trying to make your job easier.
Just connect to your db using Postgres class and pass the queries to .query() method.
The .query() method will return a custom Cursor class, if you don’t want nothing back from the db, you don’t need to store it but if you want to fetch any data, you can do it whenever you want because the Cursor class will always handle the real connection with the db. In other words you will never need to worry about closed cursors or connections because only at the exact time you request data from db the Cursor class opens the connection and then it closes it.
>>> from pypostgres.postgres import Postgres # Database connection # http://initd.org/psycopg/docs/module.html#psycopg2.connect >>> db = Postgres(database='books', user='john') >>> cursor = db.query('SELECT author FROM books;') >>> cursor.one ('George R. R. Martin',) >>> cursor.all [('George R. R. Martin',), ('J. R. R. Tolkien',)]
If you are SELECTing data, the Cursor object can help you fetch that data. You have two options:
Just pass how many result you want e.g. .fetch(n):
I consider the task of handling fechted data very important so I gave a special attention to cursor factory.
All Postgres class methods (except .mogrify()) accept a cursor_factory param that handle the desired cursor factory. For each type of cursor factory you can pass different things to get the same factory, see below.
For namedtuple results, you can pass:
For dict results, you can pass:
For RealDict results, you can pass:
The Connection class handle the entrance and exit of the database connection, opening the communication when you entered it and closing the connection when you are out.
>>> from pypostgres.connection import Connection >>> dsn = 'dbname=books user=john' >>> with Connection(dsn=dsn) as conn: >>> # do whatever you want to do >>> cursor = conn.cursor() >>> cursor.execute('SELECT author, book FROM books;') >>> data = cursor.fetchone() >>> data ('C. S. Lewis', 'The Chronicles of Narnia')