PostgreSQL – Create Tables in Python
Last Updated :
02 Sep, 2020
This article will explore the process to create new tables in the PostgreSQL database using Python.
Steps for creating PostgreSQL tables in Python
To create a new table in a PostgreSQL database, you use the following steps:
- First, construct CREATE TABLE statements.
- Next, connect to the PostgreSQL database by calling the connect() function. The connect() function returns a connection object.
- Then, create a cursor object by calling the cursor() method of the connection object.
- After that, execute the CREATE TABLE by calling the execute() method of the cursor object.
- Finally, close the communication with the PostgreSQL database server by calling the close() methods of the cursor and connection objects.
Create a Python program –
First, create a new file called create_table.py.
Second, inside the create_table.py file, define a new function called create_tables().
The create_tables() function creates four tables in the suppliers database: vendors, parts, vendor_parts, and part_drawings.
Python3
import psycopg2
from config import config
def create_tables():
commands = (
,
,
,
)
conn = None
try :
params = config()
conn = psycopg2.connect( * * params)
cur = conn.cursor()
for command in commands:
cur.execute(command)
cur.close()
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print (error)
finally :
if conn is not None :
conn.close()
if __name__ = = '__main__' :
create_tables()
|
Execute the Python program –
To execute the Python program, you use the following command:
python create_table.py
Verify the table creation –
First, log in to the PostgreSQL database server using the psql program.
Second, use the \dt command to display the table list from the suppliers database.
suppliers=# \dt
List of relations
Schema | Name | Type | Owner
--------+---------------+-------+----------
public | part_drawings | table | postgres
public | parts | table | postgres
public | vendor_parts | table | postgres
public | vendors | table | postgres
(4 rows)
As you see can see clearly from the output, we have four tables created successfully in the suppliers database.
If you use other client tools like pgAdmin, you can view the tables via the table list under the public schema.
Share your thoughts in the comments
Please Login to comment...