forked from pythontoday/python_postgresql_connection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
68 lines (54 loc) · 1.83 KB
/
main.py
File metadata and controls
68 lines (54 loc) · 1.83 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
import psycopg2
from config import host, user, password, db_name
try:
# connect to exist database
connection = psycopg2.connect(
host=host,
user=user,
password=password,
database=db_name
)
connection.autocommit = True
# the cursor for perfoming database operations
# cursor = connection.cursor()
with connection.cursor() as cursor:
cursor.execute(
"SELECT version();"
)
print(f"Server version: {cursor.fetchone()}")
# create a new table
# with connection.cursor() as cursor:
# cursor.execute(
# """CREATE TABLE users(
# id serial PRIMARY KEY,
# first_name varchar(50) NOT NULL,
# nick_name varchar(50) NOT NULL);"""
# )
# # connection.commit()
# print("[INFO] Table created successfully")
# insert data into a table
# with connection.cursor() as cursor:
# cursor.execute(
# """INSERT INTO users (first_name, nick_name) VALUES
# ('Oleg', 'barracuda');"""
# )
# print("[INFO] Data was succefully inserted")
# get data from a table
# with connection.cursor() as cursor:
# cursor.execute(
# """SELECT nick_name FROM users WHERE first_name = 'Oleg';"""
# )
# print(cursor.fetchone())
# delete a table
# with connection.cursor() as cursor:
# cursor.execute(
# """DROP TABLE users;"""
# )
# print("[INFO] Table was deleted")
except Exception as _ex:
print("[INFO] Error while working with PostgreSQL", _ex)
finally:
if connection:
# cursor.close()
connection.close()
print("[INFO] PostgreSQL connection closed")