-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpsql_test.py
More file actions
64 lines (57 loc) · 1.39 KB
/
psql_test.py
File metadata and controls
64 lines (57 loc) · 1.39 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
import psycopg2
# Connect to PostgreSQL
conn = psycopg2.connect(
database="todo",
user="todo_db_user",
host="localhost",
password="2005",
port=5432,
)
# Open a cursor to perform database operations
cur = conn.cursor()
# CREATE TABLE TASK
cur.execute(
"""
CREATE TABLE IF NOT EXISTS task (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed BOOLEAN DEFAULT FALSE
);
"""
)
# CREATE INDEX
cur.execute(
"""
CREATE INDEX IF NOT EXISTS idx_task_title ON task (title);
CREATE INDEX IF NOT EXISTS idx_task_completed ON task (completed);
"""
)
# INSEERT DATA
cur.execute(
"""
INSERT INTO task (title, description, created_at, updated_at, completed)
VALUES
('Task 1', 'Description for Task 1', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, FALSE),
('Task 2', 'Description for Task 2', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, FALSE),
('Task 3', 'Description for Task 3', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, TRUE);
"""
)
# SELECT DATA
cur.execute(
"""
SELECT * FROM task;
"""
)
# Fetch all rows from the executed query
rows = cur.fetchall()
# Print the fetched rows
for row in rows:
print(row)
# Make the changes to the database persistent
conn.commit()
# Close cursor and communication with the database
cur.close()
conn.close()