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.
Execute the Python program –
To execute the Python program, you use the following command:
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.