53 lines
2.4 KiB
Python
53 lines
2.4 KiB
Python
# https://www.freecodecamp.org/news/postgresql-in-python/
|
|
# https://www.datacamp.com/tutorial/tutorial-postgresql-python
|
|
import psycopg2
|
|
import dotenv
|
|
import os
|
|
# from icecream import ic
|
|
|
|
|
|
def main():
|
|
print("Connecting to the PostgreSQL database...")
|
|
conn = connect()
|
|
cursor = conn.cursor()
|
|
print("Creating a table")
|
|
# SERIAL: auto-incrementing integer
|
|
# VARCHAR: variable-length character string
|
|
# (50) Set the maximum length of the course_name column to 50 characters.
|
|
# UNIQUE: ensure that all values in the course_name column are unique.
|
|
# NOT NULL: ensure that the course_name column cannot have NULL values.
|
|
# (100) Set the maximum length of the course_instructor column to 100 characters.
|
|
# (20) Set the maximum length of the topic column to 20 characters.
|
|
cursor.execute("""CREATE TABLE datacamp_courses(
|
|
course_id SERIAL PRIMARY KEY,
|
|
course_name VARCHAR (50) UNIQUE NOT NULL,
|
|
course_instructor VARCHAR (100) NOT NULL,
|
|
topic VARCHAR (20) NOT NULL);
|
|
""")
|
|
print("Creating some records...")
|
|
cursor.execute("INSERT INTO datacamp_courses(course_name, course_instructor, topic) VALUES('Introduction to SQL','Izzy Weber','Julia')");
|
|
cursor.execute("INSERT INTO datacamp_courses(course_name, course_instructor, topic) VALUES('Analyzing Survey Data in Python','EbunOluwa Andrew','Python')");
|
|
cursor.execute("INSERT INTO datacamp_courses(course_name, course_instructor, topic) VALUES('Introduction to ChatGPT','James Chapman','Theory')");
|
|
cursor.execute("INSERT INTO datacamp_courses(course_name, course_instructor, topic) VALUES('Introduction to Statistics in R','Maggie Matsui','R')");
|
|
cursor.execute("INSERT INTO datacamp_courses(course_name, course_instructor, topic) VALUES('Hypothesis Testing in Python','James Chapman','Python')");
|
|
print("Committing the table to the database...")
|
|
conn.commit()
|
|
print("Closing the connection and the cursor...")
|
|
cursor.close()
|
|
conn.close()
|
|
# cursor.execute("SELECT * FROM DB_table WHERE id = 1")
|
|
|
|
|
|
def connect():
|
|
dotenv.load_dotenv()
|
|
conn = psycopg2.connect(
|
|
database=os.getenv('POSTGRES_DB'),
|
|
host=os.getenv('DB_HOST'),
|
|
port=os.getenv('DB_PORT'),
|
|
user=os.getenv('POSTGRES_USER'),
|
|
password=os.getenv('POSTGRES_PASSWORD')
|
|
)
|
|
return conn
|
|
|
|
if __name__ == "__main__":
|
|
main() |