PostgreSQL Python: Querying Data
Summary: in this tutorial, you will learn how to query data from the PostgreSQL tables in Python.
This tutorial picks up from where the Handling BLOB Data Tutorial left off.
The steps for querying data from a PostgreSQL table in Python
To query data from one or more PostgreSQL tables in Python, you use the following steps.
First, establish a connection to the PostgreSQL server by calling the connect()
function of the psycopg2
module.
If the connection is created successfully, the connect()
function returns a new Connection
object; Otherwise, it throws a DatabaseError
exception.
Next, create a new cursor by calling the cursor()
method of the Connection
object. The cursor
object is used to execute a SELECT statement.
Then, execute a SELECT
statement by calling the execute()
method. If you want to pass values to the SELECT
statement, you use the placeholder ( %s
) in the SELECT
statement and bind the input values when calling the execute()
method:
After that, process the result set returned by the SELECT statement using the fetchone()
, fetchall()
, or fetchmany()
method.
- The
fetchone()
fetches the next row in the result set. It returns a single tuple orNone
when no more row is available. - The
fetchmany(size=cursor.arraysize)
fetches the next set of rows specified by thesize
parameter. If you omit this parameter, thearraysize
will determine the number of rows to be fetched. Thefetchmany()
method returns a list of tuples or an empty list if no more rows are available. - The
fetchall()
fetches all rows in the result set and returns a list of tuples. If there are no rows to fetch, thefetchall()
method returns an empty list.
Finally, close the database connection by calling the close()
method of the Cursor
and Connection
objects
If you use context managers, you don’t need to explicitly call the close()
methods of the Cursor
and Connection
objects.
Querying data using the fetchone() method
For the demonstration purposes, we will use the parts
, vendors
, and vendor_parts
tables in the suppliers
database:
The following get_vendor()
function selects data from the vendors
table and fetches the rows using the fetchone()
method.
Output:
Querying data using the fetchall() method
The following get_parts()
function uses the fetchall()
method of the cursor object to fetch rows from the result set and display all the parts in the parts
table.
Querying data using the fetchmany() method
The following get_suppliers()
function selects parts and vendor data using the fetchmany()
method.
Output:
Download the project source code
In this tutorial, we have learned how to select data from the PostgreSQL tables in Python using the fetchone()
, fetchall()
, and fetchmany()
methods.