-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
96 lines (73 loc) · 2.81 KB
/
db.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import pymysql.cursors
from constants import *
def open_connection():
connection = pymysql.connect(
user=USER,
host=HOST,
port=PORT,
password=PASSWORD,
database=DB_NAME,
cursorclass=pymysql.cursors.DictCursor
)
return connection
def get_user(user_id):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM user WHERE user_id=%s', (user_id,))
return cursor.fetchone()
def is_user_exist(user_id):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM user WHERE user_id=%s', (user_id, ))
return bool(cursor.fetchone())
def add_user(user_id, name):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('INSERT INTO user (user_id, name) VALUES (%s, %s)', (user_id, name))
connection.commit()
def get_user_cart(user_id):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM cart_product WHERE cart_id=%s', (user_id,))
return cursor.fetchall()
def get_all_products():
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM product')
return cursor.fetchall()
def get_product(id_):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM product WHERE id=%s', (id_, ))
return cursor.fetchone()
def get_price(id_):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM price WHERE id=%s', (id_,))
return cursor.fetchone()
def add_product(user_id, product_id, product_option, color, quantity):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('''INSERT INTO cart_product (cart_id, product_id, product_option, color, quantity)
VALUES (%s, %s, %s, %s, %s)''', (user_id, product_id, product_option, color, quantity))
connection.commit()
def delete_product(id_):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('DELETE FROM cart_product WHERE id=%s', (id_, ))
connection.commit()
def delete_all_user_product(user_id):
connection = open_connection()
with connection:
with connection.cursor() as cursor:
cursor.execute('DELETE FROM cart_product WHERE cart_id=%s', (user_id, ))
connection.commit()