Repository navigation
Expand file tree
/
Copy pathpostgresql_app.py
More file actions
204 lines (160 loc) · 5.55 KB
/
Copy pathpostgresql_app.py
File metadata and controls
204 lines (160 loc) · 5.55 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import psycopg2
from psycopg2 import OperationalError
# Change these connection parameters to match your PostgreSQL server:
DB_USER = "postgres"
DB_PASSWORD = "abc123"
DB_HOST = "127.0.0.1"
DB_PORT = "5432"
def create_connection(db_name, db_user, db_password, db_host, db_port):
connection = None
try:
connection = psycopg2.connect(
database=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port,
)
print("Connection to PostgreSQL DB successful")
except OperationalError as e:
print(f"The error '{e}' occurred")
return connection
def create_database(connection, query):
connection.autocommit = True
cursor = connection.cursor()
try:
cursor.execute(query)
print("Query executed successfully")
except psycopg2.Error as e:
print(f"The error '{e}' occurred")
def execute_query(connection, query):
connection.autocommit = True
cursor = connection.cursor()
try:
cursor.execute(query)
print("Query executed successfully")
except psycopg2.Error as e:
print(f"The error '{e}' occurred")
def execute_read_query(connection, query):
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except psycopg2.Error as e:
print(f"The error '{e}' occurred")
if __name__ == "__main__":
# Connecting to the default database and creating sm_app
connection = create_connection(
"postgres", DB_USER, DB_PASSWORD, DB_HOST, DB_PORT
)
create_database_query = "CREATE DATABASE sm_app"
create_database(connection, create_database_query)
connection = create_connection(
"sm_app", DB_USER, DB_PASSWORD, DB_HOST, DB_PORT
)
# Creating tables
create_users_table = """
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
gender TEXT,
nationality TEXT
)
"""
execute_query(connection, create_users_table)
create_posts_table = """
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
description TEXT NOT NULL,
user_id INTEGER REFERENCES users(id)
)
"""
execute_query(connection, create_posts_table)
# Not shown in the tutorial: the comments and likes tables
create_comments_table = """
CREATE TABLE IF NOT EXISTS comments (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL,
user_id INTEGER REFERENCES users(id),
post_id INTEGER REFERENCES posts(id)
)
"""
create_likes_table = """
CREATE TABLE IF NOT EXISTS likes (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
post_id INTEGER REFERENCES posts(id)
)
"""
execute_query(connection, create_comments_table)
execute_query(connection, create_likes_table)
# Inserting records
users = [
("James", 25, "male", "USA"),
("Leila", 32, "female", "France"),
("Brigitte", 35, "female", "England"),
("Mike", 40, "male", "Denmark"),
("Elizabeth", 21, "female", "Canada"),
]
user_records = ", ".join(["%s"] * len(users))
insert_query = f"INSERT INTO users (name, age, gender, nationality) VALUES {user_records}"
connection.autocommit = True
cursor = connection.cursor()
cursor.execute(insert_query, users)
posts = [
("Happy", "I am feeling very happy today", 1),
("Hot Weather", "The weather is very hot today", 2),
("Help", "I need some help with my work", 2),
("Great News", "I am getting married", 1),
("Interesting Game", "It was a fantastic game of tennis", 5),
("Party", "Anyone up for a late-night party today?", 3),
]
post_records = ", ".join(["%s"] * len(posts))
insert_query = f"INSERT INTO posts (title, description, user_id) VALUES {post_records}"
connection.autocommit = True
cursor = connection.cursor()
cursor.execute(insert_query, posts)
# Not shown in the tutorial: the comments and likes records
comments = [
("Count me in", 1, 6),
("What sort of help?", 5, 3),
("Congrats buddy", 2, 4),
("I was rooting for Nadal though", 4, 5),
("Help with your thesis?", 2, 3),
("Many congratulations", 5, 4),
]
comment_records = ", ".join(["%s"] * len(comments))
insert_query = f"INSERT INTO comments (text, user_id, post_id) VALUES {comment_records}"
cursor.execute(insert_query, comments)
likes = [(1, 6), (2, 3), (1, 5), (5, 4), (2, 4), (4, 2), (3, 6)]
like_records = ", ".join(["%s"] * len(likes))
insert_query = (
f"INSERT INTO likes (user_id, post_id) VALUES {like_records}"
)
cursor.execute(insert_query, likes)
# Selecting records
select_users = "SELECT * FROM users"
users = execute_read_query(connection, select_users)
for user in users:
print(user)
# Updating table records
update_post_description = """
UPDATE
posts
SET
description = 'The weather has become pleasant now'
WHERE
id = 2
"""
execute_query(connection, update_post_description)
select_post_description = "SELECT description FROM posts WHERE id = 2"
post_description = execute_read_query(connection, select_post_description)
for description in post_description:
print(description)
# Deleting table records
delete_comment = "DELETE FROM comments WHERE id = 2"
execute_query(connection, delete_comment)