PostgreSQL Python: Insert Data Into a Table
Summary: in this tutorial, you will learn to insert one or more rows into a PostgreSQL table from Python.
This tutorial picks up from where the Creating Tables Tutorial left off.
Steps for inserting one row into a table from Python
To insert one or more rows into a table from Python, you follow these steps:
- First, connect to the PostgreSQL server.
- Next, create a
cursor
object from theconnection
object. - Then, execute the INSERT statement with values by calling the
execute()
orexecutemany()
method of thecursor
object. - After that, commit the transaction by calling the
commit()
method of theconnection
object. - Finally, obtain the inserted ID by calling the
fetchone()
method of thecursor
object.
Inserting data into a table example
We will use the vendors
table in the suppliers
database for the demonstration purposes:
1) Inserting one row into a table
First, create a new file named insert.py.
Second, define a insert_vendor()
function in the insert.py file:
The insert_vendor()
function will insert a new row into the vendors
table and return the inserted vendor_id
.
2) Inserting multiple rows into a table
The steps for inserting multiple rows into a table are similar to the steps for inserting one row.
The key difference is in the third step: instead of calling the execute()
method of the cursor
object, you use the executemany()
method.
For example, the following defines insert_many_vendors()
function that inserts multiple rows into the vendors
table:
The following uses the insert_vendor()
and insert_many_vendors()
functions to insert one and multiple rows into the vendors
table:
3) Execute the insert.py module
First, open the Command Prompt on Windows or Terminal on Unix-like systems.
Second, run the following command to execute the insert.py
module:
4) Verify the inserts
First, connect to the PostgreSQL server using the psql
:
Second, change the current database to suppliers
:
Third, retrieve data from the vendors
table:
Output:
Download the project source code
Summary
- Use the
execute()
orexecutemany()
method of thecursor
object to insert one or more rows into a table from Python.