Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added __pycache__/config.cpython-310.pyc
Binary file not shown.
19 changes: 19 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/python
from configparser import ConfigParser

def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)

# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))

return db
68 changes: 68 additions & 0 deletions connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/python
import psycopg2
from config import config

def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()

# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(
host="localhost",
database="pagila-data",
user="postgres",
password="postgres")


# create a cursor
cur = conn.cursor()

# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT * FROM public."actor"')


# display the PostgreSQL database server version
db_version = cur.fetchall()
# print(db_version)
for i in db_version:
print(i)
print("##########################################################")



cur.execute('SELECT * FROM public."category"')


# display the PostgreSQL database server version
db_version = cur.fetchone()
# print(db_version)
for i in db_version:
print(i)

print("##########################################################")

cur.execute('SELECT * FROM public."address"')


# display the PostgreSQL database server version
db_version = cur.fetchmany(50)
# print(db_version)
for i in db_version:
print(i)

# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')

if __name__ == '__main__':
connect()
1 change: 1 addition & 0 deletions database.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[postgresql] host=localhost database=Chinook_PostgreSql user=postgres password=postgres
1 change: 1 addition & 0 deletions erd diagaram1.pgerd

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions erd for pagila.pgerd

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions exercise5(insert).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import psycopg2
from config import config
# from mlxtend import psycopg2

# connection establishment
conn = psycopg2.connect(
host="localhost",
database="PyCoders",
user="postgres",
password="postgres")


# Creating a cursor object
cursor = conn.cursor()

# query to create a table in the database
# sql = (
# """
# CREATE TABLE IF NOT EXISTS public.students (
# student_id SERIAL PRIMARY KEY,
# student_name VARCHAR(255) NOT NULL
# )
# """,
# """ CREATE TABLE IF NOT EXISTS public.teachers (
# teacher_id SERIAL PRIMARY KEY,
# teacher_name VARCHAR(255) NOT NULL
# )
# """)


# # executing the query inorder to create the table
# cursor.execute(sql)
# print("Database has been created successfully !!")



# list to be inserted into table
data1 = [[1, 'Ahmet'],[2, 'Mehmet'], [3,'Meral']]
data2 = [[1, 'Ali'],[2, 'Rana'], [3,'Nihal']]

# inserting record into school table
for d1 in data1:
# postgres_insert_query = f""" INSERT INTO student (student_id, student_name) VALUES ('{d1[0]}','{d1[1]}')"""
# cursor.execute("""INSERT INTO student (student_id, student_name) VALUES ('{d1[0]}','{d1[1]}'""")
cursor.execute("INSERT into student(student_id, student_name) VALUES (%s, %s)", d1)
print("List has been inserted to student table successfully...")

for d2 in data2:
# cursor.execute("""INSERT INTO teacher (teacher_id, teacher_name) VALUES ('{d2[0]}','{d2[1]}'""")
cursor.execute("INSERT into teacher(teacher_id, teacher_name) VALUES (%s, %s)", d2)
print("List has been inserted to teacher table successfully...")


# Commit your changes in the database
conn.commit()

# print("Retrieving records from table")
cursor.execute("select * from student")
records = cursor.fetchall()

for row in records:
print("ID = ", row[0])
print("Name = ", row[1])

cursor.execute("select * from teacher")
records = cursor.fetchall()

for row in records:
print("ID = ", row[0])
print("Name = ", row[1])

# Closing the connection
conn.close()
46 changes: 46 additions & 0 deletions exercise5(table).py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import psycopg2
from config import config


def create_tables():
""" create tables in the PostgreSQL database"""
commands = (
"""
CREATE TABLE student (
student_id SERIAL PRIMARY KEY,
student_name VARCHAR(255) NOT NULL
)
""",
""" CREATE TABLE teacher (
teacher_id SERIAL PRIMARY KEY,
teacher_name VARCHAR(255) NOT NULL
)
""")

conn = None
try:
# read the connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(
host="localhost",
database="PyCoders",
user="postgres",
password="postgres")
cur = conn.cursor()
# create table one by one
for command in commands:
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()


if __name__ == '__main__':
create_tables()