
fetchall () # print out the records using pretty print # note that the NAMES of the columns are not shown, instead just indexes. execute ( "SELECT * FROM my_table" ) # retrieve the records from the database records = cursor. connect ( conn_string ) # conn.cursor will return a cursor object, you can use this cursor to perform queries cursor = conn. #!/usr/bin/python import psycopg2 import sys import pprint def main (): conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'" # print the connection string we will use to connect print "Connecting to database \n -> %s " % ( conn_string ) # get a connection, if a connect cannot be made an exception will be raised here conn = psycopg2. Catch and print a connection error if one occurs.
#Python connect to postgresql server code
You may want to copy the examples into your favorite code editor for syntax highlighting!Īll code examples were tested on Python 2.6 running OpenSUSE Linux.Ĭonnect to the Postgres Database using authentication. I will not assume you are perfectly familiar with Python in the below examples therefore I have provided an excessive amount of comments and each example is a full-fledged script instead of just a snippet. To see the Python 2 specific examples, use this last version from 2015. The cookbook style remains, however the page is under development to modernize for Python 3. This page was originally developed by Bendermott, with contributions from Jonjensen and others.

Connection pooling (example to be added later).Return columns as a Python Dictionary (Hash) with column names.


