PostgreSQL Python: Create Tables
Summary: in this tutorial, you will learn how to create new tables in the PostgreSQL database using Python.
This tutorial picks up from where the Connecting to PostgreSQL database server tutorial left off.
Steps for creating tables in PostgreSQL from Python
To create a new table in a PostgreSQL database, you use the following steps:
- First, connect to the PostgreSQL server by calling the
connect()
function. Theconnect()
function returns aconnection
object. - Second, create a
cursor
object by calling thecursor()
method of theconnection
object. - Third, execute the
CREATE TABLE
by calling theexecute()
method of thecursor
object. - Finally, close the connection.
If you use the with
statement, you don’t need to explicitly close the connection.
Creating tables in Python example
Let’s take an example of creating tables from Python.
1) Create a Python program
First, create a new file in the project directory called create_tables.py
.
Second, define a new function called create_tables()
in the create_tables.py
module:
How it works.
First, initialize a list of CREATE TABLE
statements:
Next, read the connection parameters using the load_config()
function of the config
module:
Then, connect to the PostgreSQL server using the connect()
function of the psycopg2
module. The connect()
function returns a connection
object:
The with
statement will close the database connection automatically.
After that, create a new cursor
object from the connection
object using the cursor()
function:
The with
statement will also automatically close the cursor once it is no longer in use.
Finally, iterate over the command in the commands
list and execute each of them using the execute()
method:
The create_tables()
function will create four tables in the suppliers
database:
vendors
– stores vendor data.parts
– stores the part data.vendor_parts
– stores the links between vendors and parts.part_drawings
– stores the drawing of the parts.
The following diagram illustrates the tables and their relationships:
2) Execute the create_tables.py script
The following command executes the create_tables.py
module that calls the create_tables()
function:
3) Verify the table creation
First, open the Command Prompt on Windows or Terminal on Unix-like systems and connect to the PostgreSQL server using the psql
client tool.
It’ll prompt you for a password for the postgres
user.
Second, change the current database to suppliers
:
Third, show tables in the suppliers
database using the \dt
command:
Output:
The output indicates that the suppliers
database has four tables.
Download the project source code
Summary
- Call the
execute()
method of theCursor
object to execute aCREATE TABLE
statement to create a new table in the database.