PostgreSQL Python Connector

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PostgreSQL Python Connector

Introduction

"PostgreSQL Python" connector enables Python programs to access PostgreSQL databases, the connector uses an API which is compliant with the Python Database API Specification.

There are several Python drivers for PostgreSQL. Here is a list of drivers :

Connector License Platforms Python versions
Psycopg LGPL Unix, Win32 2.4-3.2
PyGreSQL BSD Unix, Win32 2.3-2.6
ocpgdb BSD Unix 2.3-2.6
py-postgresql BSD any (pure Python) 3.0+
bpgsql LGPL any (pure Python) 2.3-2.6
pg8000 BSD any (pure Python) 2.5+ / 3.0+

Psycopg is the most popular PostgreSQL adapter for the Python programming language. At its core, it fully implements the Python DB API 2.0 specifications. Several extensions allow access to many of the features offered by PostgreSQL.

Psycopg is released under the terms of the GNU Lesser General Public License, allowing use of both free and proprietary software.

Psycopg features : 
Psycopg is written mostly in C and wraps the libpq library with the result of being both fast and secure.

  • Supports Python versions from 2.5 to 3.4.
  • Supports PostgreSQL versions from 7.4 to 9.4.
  • Fully compliant implementation of the Python DB API specification for database adapters.
  • Thread-safe: threads can use different connections or share the same connection.
  • Asynchronous nonblocking I/O also integrated with coroutine-based libraries.
  • Adaptation of many Python objects to database type: tuples to records, lists to an array, dictionaries to hstore, flexible JSON support.
  • Extendible with new adapters to convert Python objects to SQL syntax and type casters to convert PostgreSQL types back into Python objects.
  • Server-side cursors.
  • COPY support.
  • Large objects support.
  • Can send and receive asynchronous notification.
  • Support for two-phase commit.

Download and installation

The python connector runs on any platform where Python is installed. Python comes preloaded on many Linux distribution or Unix-like systems, such as Mac OS X and FreeBSD.

Install from a package

Linux : 
On Debian, Ubuntu and other deb-based distributions execute the following command to install the package with all its dependencies.

sudo apt-get install python-psycopg2

Mac OS X : 
Psycopg is available as a fink package in the unstable tree: you may install it with:

fink install psycopg2-py27

The library is also available on MacPorts try :

sudo port install py27-psycopg2

Install Python Connector on Microsoft Windows

Before installing the Connector on Windows :

  • To complete the installation operation, root or administrator privileges may be required.
  • Before installing the Python distribution on your system, enable python.exe in Windows %PATH% setting ( path environment variable) or manually add it to, if it is not enabled.

win-psycopg is a Windows port of the psycopg python-postgresql database interface Version: 2.6.0.

Release Files :

Python
Version
x86 Release
(for x86 versions of Python)
64 bit (AMD64/EM64T/x64) Release
(for 64 bit versions of Python)
Python 2.6 psycopg2-2.6.0.win32-py2.6-pg9.4.1-release.exe psycopg2-2.6.0.win-amd64-py2.6-pg9.4.1-release.exe
Python 2.7 psycopg2-2.6.0.win32-py2.7-pg9.4.1-release.exe psycopg2-2.6.0.win-amd64-py2.7-pg9.4.1-release.exe
Python 3.2 psycopg2-2.6.0.win32-py3.2-pg9.4.1-release.exe psycopg2-2.6.0.win-amd64-py3.2-pg9.4.1-release.exe
Python 3.3 psycopg2-2.6.0.win32-py3.3-pg9.4.1-release.exe psycopg2-2.6.0.win-amd64-py3.3-pg9.4.1-release.exe
Python 3.4 psycopg2-2.6.0.win32-py3.4-pg9.4.1-release.exe psycopg2-2.6.0.win-amd64-py3.4-pg9.4.1-release.exe

Python psycopg2 module APIs

The basic Psycopg usage is common to all the database adapters implementing the DB API 2.0 protocol. 

Connect to an existing database :

import psycopg2
conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")
print("Database Connected....")

Output :

Database Connected....

Python Command to open a cursor to perform database operations :

cur = conn.cursor()

Creates a new table :

  1. import psycopg2  
  2. conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")  
  3. print("Database Connected....")  
  4. cur = conn.cursor()  
  5. cur.execute("CREATE TABLE test(id serial PRIMARY KEY, sname CHAR(50), roll_num integer);")  
  6. print("Table Created....")  
  7. conn.commit()  
  8. conn.close()  

Output :

Database Connected....
Table Created....

Insert some records :

  1. import psycopg2  
  2. conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")  
  3. cur = conn.cursor()  
  4. cur.execute("INSERT INTO test (id, sname, roll_num)   
  5.       VALUES (10'Sara'3)");  
  6.   
  7. cur.execute("INSERT INTO test (id, sname, roll_num)   
  8.       VALUES (20'Ema'4)");  
  9.   
  10. cur.execute("INSERT INTO test (id, sname, roll_num)   
  11.       VALUES (30'Drabir'2)");  
  12.   
  13. cur.execute("INSERT INTO test (id, sname, roll_num)   
  14.       VALUES (40'Surya'1)");  
  15.   
  16. conn.commit()  
  17. print("Records created successfully");  
  18. conn.close()  

Output :

Records created successfully.

Select all the recods :

  1. import psycopg2  
  2. conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")  
  3. cur = conn.cursor()  
  4. cur.execute("SELECT id, sname, roll_num from test")  
  5. print("ID   Roll No. Student Name")  
  6. print("--------------------------")   
  7. rows = cur.fetchall()  
  8. for row in rows:  
  9.    print(row[0],' ',str(row[2]).strip(),'      ',row[1].strip())  
  10.   
  11. conn.close()  

Output :

ID   Roll No. Student Name
--------------------------
10   3        Sara
20   4        Ema
30   2        Drabir
40   1        Surya

Updates columns of existing rows in the named table with new values :

  1. import psycopg2  
  2. conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")  
  3. cur = conn.cursor()  
  4. cur.execute("UPDATE test set roll_num = 5 where ID=10")  
  5. conn.commit  
  6. cur.execute("SELECT id, sname, roll_num from test")  
  7. print("ID   Roll No. Student Name")  
  8. print("--------------------------")   
  9. rows = cur.fetchall()  
  10. for row in rows:  
  11.    print(row[0],' ',str(row[2]).strip(),'      ',row[1].strip())  
  12.   
  13. conn.close()  

Output :

ID   Roll No. Student Name
--------------------------
20   4        Ema
30   2        Drabir
40   1        Surya
10   5        Sara

Delete Record(s) :

  1. import psycopg2  
  2. conn = psycopg2.connect(database="postgres", user="postgres", password="datasoft123", host="127.0.0.1", port="5432")  
  3. cur = conn.cursor()  
  4. cur.execute("DELETE from test where ID=10;")  
  5. conn.commit  
  6. cur.execute("SELECT id, sname, roll_num from test")  
  7. print("ID   Roll No. Student Name")  
  8. print("--------------------------")   
  9. rows = cur.fetchall()  
  10. for row in rows:  
  11.    print(row[0],' ',str(row[2]).strip(),'      ',row[1].strip())  
  12.   
  13. conn.close()  

Output :

ID   Roll No. Student Name
--------------------------
20   4        Ema
30   2        Drabir
40   1        Surya