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 pathconnect.py
More file actions
42 lines (33 loc) · 1 KB
/
Copy pathconnect.py
File metadata and controls
42 lines (33 loc) · 1 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
#!/usr/bin/python
import psycopg2
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# connect to the PostgreSQL server
print('Connecting to the pagila database...')
conn = psycopg2.connect(
host = 'localhost',
database = 'pagila',
user = 'postgres',
password = 3678)
# create a cursor
cur = conn.cursor()
# execute a statement
cur.execute('SELECT * FROM public.actor')
# display the result
result = cur.fetchmany(5)
# result = cur.fetchall()
# result = cur.fetchone()
for r in result:
print(r)
# 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()