How to query data using fetchall()

Python




# GET THE CONNECTION OBJECT
conn = get_connection()
# CREATE A CURSOR USING THE CONNECTION OBJECT
curr = conn.cursor()
# EXECUTE THE SQL QUERY
curr.execute("SELECT * FROM students;")
# FETCH ALL THE ROWS FROM THE CURSOR
data = curr.fetchall()
# PRINT THE RECORDS
for row in data:
    print(row)
# CLOSE THE CONNECTION
conn.close()


Output:

Output for fetchall()

In the above code, we create a connection and query using SELECT * FROM students which fetches the entire dump of the students table. In order to query data in the python code, we can make use of fetchall(). The fetchall() method fetches all the records that we got from our SQL query (the SELECT query in this case) and provides them in a list. The list consists of tuples where each tuple consists of all the column values present in the particular record or row.

PostgreSQL Python – Querying Data

Psycopg2 acts as a bridge between Python applications and PostgreSQL databases. Widely employed in diverse Python systems, from web applications to data analysis tools and other software projects, Psycopg2 enables developers to execute queries and manipulate data stored in PostgreSQL databases.

In this article, we will see What Psycopg 2?, and how to use PostgreSQL using pyscopg2 in Python for executing query data.

Similar Reads

What is Psycopg2?

Psycopg2 is a PostgreSQL adapter for Python programming language. It acts as a bridge between Python and the PostgreSQL database that allows Python applications to interact with and manipulate data stored in a PostgreSQL database. It is widely used in Python systems to develop applications that require interaction with PostgreSQL databases including web applications, data analysis tools, and tool software projects....

How to install Psycopg2

To establish a connection to the PostgreSQL server, we will make use of the pscopg2 library in Python. You can install psycopg2 using the following command:...

How to Query data using psycopg2

...

How to query data using fetchall()

Let us look at how can we query data using the psycopg2 library....

How to query data using fetchone()

Python # GET THE CONNECTION OBJECT conn = get_connection() # CREATE A CURSOR USING THE CONNECTION OBJECT curr = conn.cursor() # EXECUTE THE SQL QUERY curr.execute("SELECT * FROM students;") # FETCH ALL THE ROWS FROM THE CURSOR data = curr.fetchall() # PRINT THE RECORDS for row in data:     print(row) # CLOSE THE CONNECTION conn.close()...

How to query data using fetchmany()

...

Contact Us