Do loop in Postgresql Using Psycopg2 Python
Last Updated :
28 Apr, 2025
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes in the SQL statement as a string. Commit the changes to the database using the conn.commit method, and Close the cursor and the connection using the cur.close and conn.close methods, respectively. Before starting let's understand some of the terminologies that we will use in this article:
- psycopg2: A popular Python library that provides a simple way to interact with PostgreSQL databases from Python scripts.
- SQL: Structured Query Language, a standard language used to interact with relational databases.
- SELECT: A SQL statement used to retrieve data from a database table.
- INSERT: A SQL statement used to insert data into a database table.
- UPDATE: A SQL statement used to update existing data in a database table.
Note: To run this code you need to first create a table in your postgres named 'mytable'.
Use a Loop to Insert Multiple Rows into a Table
Import the psycopg2 library. Connect to the database, In this section of code, you connect to a PostgreSQL database by creating a conn object and passing it several parameters such as:
- database: The name of the database you want to connect to.
- user: The username used to connect to the database.
- password: The password for the specified user.
- host: The hostname of the server where the database is located.
- port: The port number used to connect to the database.
Then Create a cursor, A cursor is a control structure used to traverse and fetch the data stored in a database. In this code, you create a cursor by calling the cursor method on the conn object. The data you want to insert into the database is defined as a list of tuples in the data variable. Each tuple represents a row of data, with the first element being the id and the second element being the name. The query used for insertion is:
INSERT INTO mytable (id, name) VALUES (%s, %s)"
After that use for loop to insert data, this section uses a for loop to insert each row of data into the database. You define an SQL query in the SQL variable, with placeholders %s for the values that you want to insert. You then use the execute method on the cursor cur object, passing in the SQL query and the current row of data as parameters. Once the data has been inserted into the database, you need to commit the changes to the database. You do this by calling the commit method on the conn object. Finally, you close the cursor by calling the close method on the cur object, and you close the connection by calling the close method on the conn object.
Python3
import psycopg2
# Connect to the database
conn = psycopg2.connect(
database="postgres",
user='postgres',
password='123456789',
host='localhost',
port='5432'
)
# Create a cursor
cur = conn.cursor()
# Define the data to be inserted
data = [(1, 'John Doe'), (2, 'Jane Doe'), (3, 'Jim Doe')]
# Use a for loop to insert each row of data into the table
for row in data:
sql = "INSERT INTO mytable (id, name) VALUES (%s, %s)"
cur.execute(sql, row)
# Commit the changes to the database
conn.commit()
print(f"{data}\nData is successfully inserted")
# Close the cursor and the connection
cur.close()
conn.close()
Output:
 Use a Loop to Fetch all the Rows in a Table
This code also uses a similar approach only the difference is we are displaying data from the table in the database using fetchall() function and looping. To select complete data from mytable we use this query: SELECT * FROM mytable. And to apply it on each row we use it for loop and print IDs and Names. And Commit the changes and Close the cursor with the connection.Â
Python3
import psycopg2
# Connect to the database
conn = psycopg2.connect(
database="postgres",
user='postgres',
password='123456789',
host='localhost',
port='5432'
)
# Create a cursor
cur = conn.cursor()
# Execute a SELECT statement to retrieve
# all the rows from the table
cur.execute("SELECT * FROM mytable")
# Fetch all the rows using a for loop
rows = cur.fetchall()
for row in rows:
id, name = row
print(f"ID: {id}, Name: {name}")
# Close the cursor and the connection
cur.close()
conn.close()
Output:
Â
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