-
Notifications
You must be signed in to change notification settings - Fork 8
/
python_postgresql_cheatcodes.py
78 lines (68 loc) · 1.64 KB
/
python_postgresql_cheatcodes.py
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
#>> pip install psycopg2
import psycopg2
from psycopg2 import Error
connect = psycopg2.connect(
user="postgres",
password="arunisto",
host="localhost",
port="5433",
database="sample", #change the database after creating it before it's template1(default)
)
#cursor
cursor = connect.cursor()
#connect.autocommit = True
#creating database
"""
sql = "CREATE DATABASE sample;"
try:
cursor.execute(sql)
print("Database Created Successfully!")
except (Exception, Error) as e:
print(e)
"""
#creating table
"""
sql = ("CREATE TABLE logs (id SERIAL PRIMARY KEY,"
"text VARCHAR(250), name VARCHAR(100),"
"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);")
cursor.execute(sql)
connect.commit()
print("Table Created Successfully!")
"""
#Inserting data into table
"""
sql = "INSERT INTO logs (text, name) VALUES (%s, %s)"
data = ("This is sample text", "arunisto")
cursor.execute(sql, data)
connect.commit()
print("Data Added Successfully!")
"""
#fetching data from the table
"""
sql = "SELECT * FROM logs;"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
"""
#fetching one data from table
"""
sql = "SELECT * FROM logs WHERE id=1;"
cursor.execute(sql)
result = cursor.fetchone()
print(result)
"""
#updating data on table
"""
sql = "UPDATE logs SET name=%s WHERE id=%s;"
data = ("arun arunisto", "1")
cursor.execute(sql, data)
connect.commit()
print("Data updated successfully!")
"""
#deleting data from table
sql = ("DELETE FROM logs WHERE id=%s")
data = ("1",)
cursor.execute(sql, data)
connect.commit()
print("Deleted Successfully!")
connect.close()