This repository has been archived by the owner on Sep 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
120 lines (89 loc) · 2.47 KB
/
main.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""
# INSTALL
pip install mysql-connector-python
# IMPORT
import mysql.connector
# CONNECT
connection = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="banco"
)
cursor = connection.cursor()
# CREATE
nome_produto = "todynho"
valor = 3
command = f'INSERT INTO vendas (nome_produto, valor) VALUES ("{nome_produto}", {valor})'
cursor.execute(command)
connection.commit()
# READ
command = 'SELECT * FROM vendas'
cursor.execute(command)
result = cursor.fetchall()
for product in result:
print(f"{product[0]} - {product[1]} - R${product[2]:.2f}")
output example:
3 - todynho - R$4.00
3 - todynho - R$6.00
# UPDATE
nome_produto = "todynho"
valor = 3
command = f'UPDATE vendas SET valor = {valor} WHERE nome_produto = "{nome_produto}"'
cursor.execute(command)
connection.commit()
# DELETE
nome_produto = "todynho"
command = f'DELETE FROM vendas WHERE nome_produto = "{nome_produto}"'
cursor.execute(command)
connection.commit()
# CLOSE
cursor.close()
connection.close()
"""
import mysql.connector
def connect_db():
# CONNECT
connection = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="banco"
)
cursor = connection.cursor()
return connection, cursor
def create(connection, cursor, nome_produto, valor):
# CREATE
command = f'INSERT INTO vendas (nome_produto, valor) VALUES ("{nome_produto}", {valor})'
cursor.execute(command)
connection.commit()
def read(cursor):
# READ
command = 'SELECT * FROM vendas'
cursor.execute(command)
return cursor.fetchall()
def update(connection, cursor, set_cmd, condition):
# UPDATE
command = f'UPDATE vendas SET {set_cmd} WHERE {condition}'
cursor.execute(command)
connection.commit()
def delete(connection, cursor, condition):
# DELETE
command = f'DELETE FROM vendas WHERE {condition}'
cursor.execute(command)
connection.commit()
def main():
connection, cursor = connect_db()
create(connection, cursor, "todynho", 4)
table = read(cursor)
for product in table:
print(f"{product[0]} - {product[1]} - R${product[2]:.2f}")
update(connection, cursor, 'valor = 6', 'nome_produto = "todynho"')
table = read(cursor)
for product in table:
print(f"{product[0]} - {product[1]} - R${product[2]:.2f}")
delete(connection, cursor, 'nome_produto = "todynho"')
cursor.close()
connection.close()
if __name__ == '__main__':
main()