PostgreSQL – Create table using Python
Last Updated :
30 Aug, 2020
This article explores the process of creating table in The PostgreSQL database using Python.
Prerequisites:
- psycopg2 module
- sample database
Creating a Table:
To create a table in the database use the following steps:
- First create a CREATE TABLE statement
- Second establish a connection to the database using the connect() function
- Third construct a cursor object by using the cursor() method.
- Now execute the above created CREATE TABLE statement using the execute function.
Example:
In this example we have already created a Database called school. We will be adding tables to it. To do so we created a file called create_table.py and defined a create_table() function as shown below:
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()
|
This will successfully create the tables :
- student
- grade
- student_grade
- student_detail
To verify so use the below command through the client tool of the same database(ie, school):
\dt
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...