Python Psycopg – Cursor class
Last Updated :
26 Jan, 2022
The cursor class Enables Python scripts to use a database session to run PostgreSQL commands. The connection class is what creates cursors.
cursor() method: They are permanently connected to the connection, and all instructions are run in the context of the database session covered by the connection. Cursors generated from the same connection aren’t separated, which means that any alterations made to the database by one cursor are incontinently visible to the others. Cursors made from separate connections can be isolated or not, depending on the insulation position of the connections.
Cursors are not thread-safe, a multithreaded application can construct multiple cursors from a single connection, and each cursor should be used by a single thread.
Create a simple cursor:
in the below code we form a connection to the “Hospital_database” and a cursor is created using connection.cursor() method.
Python3
import psycopg2
conn = psycopg2.connect(
database = "Hospital_database" , user = 'postgres' ,
password = 'pass' , host = '127.0.0.1' , port = '5432'
)
conn.autocommit = True
cursor = conn.cursor()
|
Methods in Cursor Class
execute() method:
Prepare a database operation and run it (query or command). Parameters can be provided in the form of a series or a mapping, and they’ll be tied to variables in the operation. Positional (% s) or named (% (name)s) placeholders are used to specify variables.
None is returned by the method.
Syntax: execute(operation[, parameters])
Example:
Python3
sql =
cursor.execute(sql)
|
executemany() method:
Build a database action (query or command) and run it against all of the parameter tuples or mappings in a sequence of parameters. The function is especially useful for database update instructions because it discards any result set produced by the query.
Syntax executemany(operation, sequence_of_parameters)
Example:
Python3
cursor.executemany( "INSERT INTO classroom VALUES(%s,%s,%s)" ,
values)
|
fetchall() method:
All (remaining) rows of a query result are fetched and returned as a list of tuples. If there are no more records to fetch, an empty list is returned.
Syntax: cursor.fetchall()
Example:
Python3
sql =
cursor.execute(sql)
results = cursor.fetchall()
print (results)
|
Output:

fetchone() method:
Returns a single tuple if the next row of a query result set is available, or None if no further data is available.
Syntax: cursor.fetchone()
Example:
Python3
sql =
cursor.execute(sql)
result = cursor.fetchone()
print (result)
|
Output:

fetchmany() method:
Returns a list of tuples after fetching the next set of rows from a query result. if there are no more rows available, a blank list is returned.
The argument specifies the number of rows to fetch each call. The cursor’s array size specifies the number of rows to be fetched if it is not specified. The procedure should attempt to retrieve as many rows as the size parameter specifies.
Syntax: cursor. fetchmany([size=cursor.arraysize])
Example:
The below example is to fetch the first two rows.
Python3
sql =
cursor.execute(sql)
result = cursor.fetchmany( 2 )
print (result)
|
Output:

callproc() method:
Use the name of a stored database procedure to invoke it. Each argument that the procedure expects must have its own entry in the parameter sequence. The call returns a changed duplicate of the input sequence as the result. The input parameters are left alone, while the output parameters maybe get replaced with new values.
Syntax: curor.callproc(procname[, parameters])
mogrify() method:
After the arguments have been bound, a query string is returned. The string returned is the same as what was sent to the database if you used the execute() method or anything similar.
Syntax: cursor.mogrify(operation[, parameters])
Example:
Python3
args = ',' .join(cursor.mogrify( "(%s,%s,%s)" , i).decode( 'utf-8' )
for i in values)
|
close() method:
used to close the cursor. From this point forth, the cursor will be inoperable; if any operation is performed with the cursor, an InterfaceError will be raised.
Syntax: curor.close()
Let’s see the below example to see the complete working of the cursor object.
A connection is established to the “Employee_db” database. a cursor is created using the conn.cursor() method, select SQL statement is executed by the execute() method and all the rows of the Table are fetched using the fetchall() method.
Python3
import psycopg2
conn = psycopg2.connect(
database = "Employee_db" , user = 'postgres' ,
password = 'root' , host = 'localhost' , port = '5432'
)
conn.autocommit = True
cursor = conn.cursor()
sql =
cursor.execute(sql)
results = cursor.fetchall()
print (results)
conn.commit()
conn.close()
|
Output:
[(1216755, ‘raj’, ‘data analyst’, 1000000, 2, ‘1216755raj’), (1216756, ‘sarah’, ‘App developer’, 60000, 3, ‘1216756sarah’), (1216757, ‘rishi’, ‘web developer’, 60000, 1, ‘1216757rishi’), (1216758, ‘radha’, ‘project analyst’, 70000, 4, ‘1216758radha’), (1216759, ‘gowtam’, ‘ml engineer’, 90000, 5, ‘1216759gowtam’), (1216754, ‘rahul’, ‘web developer’, 70000, 5, ‘1216754rahul’), (191351, ‘divit’, ‘100000.0’, None, None, ‘191351divit’), (191352, ‘rhea’, ‘70000.0’, None, None, ‘191352rhea’)]
Similar Reads
Python Psycopg - Connection class
The connection to a PostgreSQL database instance is managed by the connection class. It's more like a container for a database session. The function connect() is used to create connections to the database. The connect() function starts a new database session and returns a connection class instance.
3 min read
Comparing psycopg2 vs psycopg in Python
PostgreSQL is a powerful, open-source relational database management system known for its robustness, extensibility, and standards compliance. It supports a wide range of data types and complex queries, making it suitable for various applications, from small web applications to large enterprise syst
8 min read
Python psycopg2 - Read Image
Psycopg2 is the most widely used PostgreSQL database adapter for Python. The creation, update, modification, and deletion of PostgreSQL databases and tables, as well as the execution of queries and the retrieval of results, are all supported by it. This library also supports transaction management,
9 min read
What is a PyMongo Cursor?
MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) t
2 min read
wxPython - Change cursor for ToolBar
In this article will learn how can we change the cursor to a custom image cursor when it hovers over the toolbar. To do this we need to follow some steps as follows. Step 1: Create wx.Image object of the image you like. Step 2: Create wx.Cursor object passing image as parameter. Step 3: Set cursor f
1 min read
How to Close Connections in psycopg2 using Python
PostgreSQL database connection in psycopg2 is somewhat of a session with the database. When the connection is created it makes a path through which Python application is able to communicate with the database. This connection enables you to run a command in SQL, perform one or more operations that ar
4 min read
Python Psycopg2 - Concatenate columns to new column
In this article, we are going to see how to concatenate multiple columns of a table in a PostgreSQL database into one column. To concatenate two or more columns into one, PostgreSQL provides us with the concat() function. Table for demonstration: In the below code, first, a connection is formed to t
2 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Comparing psycopg2-binary vs psycopg2 in Python
When working with PostgreSQL databases in Python, one of the most critical decisions is choosing the right library for database connectivity. psycopg2 is the go-to library for many developers due to its efficiency and extensive feature set. However, there's often confusion between psycopg2 and its s
7 min read
Create Classes Dynamically in Python
A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects
2 min read