-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_data_mysql.py
More file actions
42 lines (36 loc) · 1.08 KB
/
read_data_mysql.py
File metadata and controls
42 lines (36 loc) · 1.08 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
import mysql.connector
import string
from mysql.connector import Error
def conectar():
"""Conecta al servidor MySQL."""
try:
conexion = mysql.connector.connect(
host='127.0.0.1',
user='admin',
password='1234',
database='my_bd'
)
if conexion.is_connected():
print('Conexión exitosa.')
return conexion
except Error as e:
print(f"Error al conectar a MySQL: {e}")
def leer_datos(conexion):
#tengo que saber como esta estructurada la tabla y sus campos
try:
cursor = conexion.cursor()
query = "select * from almacen;"
cursor.execute(query)
for (id_producto,producto,precio) in cursor:
print("{},{},{}".format(id_producto,producto,precio))
except Error as e:
print(f"Error al leer datos: {e}")
finally:
if conexion.is_connected():
cursor.close()
conexion.close()
print('Conexión cerrada.')
# Uso de las funciones
conexion = conectar()
if conexion:
leer_datos(conexion)