psycopg2 python adapter for PostgreSQL databases
-
psycopg2 is a popular and open source python library to connect to PostgreSQL databases. It is thread safe, which means several cursors can be created from the same connection and change made from one cursor will automatically reflect in other cursors of the same connection.
psycopg2 is the complete rewrite of psycopg with much more features. psycopg2 library is performance oriented and is designed to handle applications that has large number of concurrent transactions. Supports unicode characters and python version 3 and higher.
This article covers all the major functionalities with short explanations and easy to use code samples. -
Contents
-
Install psycopg2
Download and install the latest version of python from Python Website if not already done.
Install psycopg2 using the command: pip install psycopg2
Or to installed pre-compiled binary version, use: pip install psycopg2-binary
-
Check if psycopg2 installed successfully
Type command pip freeze
Should give an output like:psycopg2==2.9.2
-
Connect to Database
To connect to PostgreSQL database using psycopg2, we have to import psycopg2, define connection string and then use psycopg2.connect() method. Copy the below code to a python file in your Virtual Environment and run it.
import psycopg2 s = '' #Your server name d = '' #Your database name u = '' #Your login p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) print(conn)
To run the code, use command python filename.py
On running the code should see the below output if connection successful.
connection object at 0x000001B62D641360; dsn: 'user=username password=xxx dbname=dbname host=hostname', closed: 0
-
psycopg2 Cursor Object
psycopg2 Cursor object represents a database cursor, that we can use to manage data from an SQL query. We can create multiple cursors from same connection. Any changes done to data using one cursor is visible to the other cursor immediately.
-
Read data from table
To read data from PostgreSQL database, execute the command and use fetchall() method.
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("SELECT * FROM TableName") for row in cursor.fetchall(): print(row)
-
Insert data to table
Insert to table sample below.
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("INSERT INTO TableName (id, name) VALUES (%s, %s)", (someid, 'somename')) conn.commit()
-
Update data to table
Update data to table sample below.
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("UPDATE TableName SET name = ? WHERE id = ?", 'somename', someid) conn.commit()
-
Delete data from table
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("DELETE FROM TableName WHERE id = ?", someid) conn.commit()
-
Call a stored procedure in psycopg2
Stored procedure without parameters
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("CALL updateall()") conn.commit()
Stored procedure with parameters
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("CALL updatebyid(%s, %s)", str(id), name) #convert all params to string conn.commit()
-
Call a function in psycopg2
Function without parameters
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("SELECT getallfunc()") for row in cursor.fetchall(): print(row)
Function with parameters
import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() cursor.execute("SELECT getallbyidfunc(%s)", str(1)) #convert all params to string for row in cursor.fetchall(): print(row)
-
psycopg2 fetchone() and fetchall()
fetchone() returns next row.
fetchall() returns all remaining rows.import psycopg2 s = '' #Your server(host) name d = '' #Your database name u = '' #Your login user p = '' #Your login password conn = psycopg2.connect(host=s, user=u, password=p, database=d) cursor = conn.cursor() c = cursor.execute("SELECT * FROM TableName") for row in cursor.fetchone(): print(row) for row in cursor.fetchall(): print(row)
-
psycopg2 commit() and rollback()
commit() Commits all transactions since last commit or rollback.
rollback() Rolls back all uncommitted transactions. -
psycopg2 Close Connection
Make sure to close connection after use. Use conn.close()
-
psycopg2 Samples