forked from fenyx-it-academy/Class7-Database-Module-Week8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise5.py
More file actions
59 lines (47 loc) · 1.53 KB
/
Copy pathexercise5.py
File metadata and controls
59 lines (47 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import psycopg2
# from config import config
def connect():
"""connect to the PostgreSQL database server"""
conn = None
try:
#connect to the PostgreSQL server
print('Connecting to the PyCoders database...')
conn = psycopg2.connect(
host = "localhost",
database = "PyCoders",
user = "postgres",
password = 3678)
conn.autocommit = True
#create table for students
cur = conn.cursor()
file = open('PyCoders.sql', 'r')
sql = file.read()
file.close()
commands = sql.split(';')[:-1]
for cmd in commands:
try:
cur.execute(cmd)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
select_query = 'SELECT * FROM students'
cur.execute(select_query)
result = cur.fetchmany(5)
# result = cur.fetchall()
# result = cur.fetchone()
print(result)
select_query2 = 'SELECT * FROM teachers'
cur.execute(select_query2)
result = cur.fetchmany(5)
# result = cur.fetchall()
# result = cur.fetchone()
print(result)
# #close the communicaton 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()