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
# importing packages
import psycopg2
# forming the connection
conn = psycopg2.connect(
database="Hospital_database", user='postgres',
password='pass', host='127.0.0.1', port='5432'
)
# Setting auto commit to True
conn.autocommit = True
# Creating a cursor object using the
# cursor() method
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 = '''SELECT * FROM employee;'''
# executing the sql command
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
# executing the sql statement
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 = '''SELECT * FROM employee;'''
# executing the sql command
cursor.execute(sql)
# fetching all the rows
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 = '''SELECT * FROM employee;'''
# executing the sql command
cursor.execute(sql)
# fetching one row
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 = '''SELECT * FROM employee;'''
# executing the sql command
cursor.execute(sql)
# fetching first two rows
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
# cursor.mogrify() to insert multiple values
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
# importing packages
import psycopg2
# establishing connection
conn = psycopg2.connect(
database="Employee_db", user='postgres',
password='root', host='localhost', port='5432'
)
# setting autocommit to True
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
sql = '''SELECT * FROM employee;'''
# executing the sql command
cursor.execute(sql)
# fetching all the rows
results = cursor.fetchall()
print(results)
# committing changes
conn.commit()
# closing connection
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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read