Python - Consulta MySQL desde una función

 
Vista:
Imágen de perfil de Tomas

Consulta MySQL desde una función

Publicado por Tomas (7 intervenciones) el 20/12/2021 01:08:59
Buenas, tengo un problema duda respecto a insertar datos en la base de datos mediante consultas mysql.

Tengo el archivo 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
from tkinter import *
from tkinter import ttk
from conexion import *
 
####### FUNCIONES #######
 
def click():
    ttk.Label(mainframe, text="Haz echo CLICK").grid(column=40, row=70, sticky=W)
    ttk.Button(mainframe, text="BOTON 2", command=click2).grid(column=40, row=90, sticky=W)
 
def click2():
    ttk.Label(mainframe, text="POR FIN!!").grid(column=40, row=110, sticky=W)
    ttk.Button(mainframe, text="BOTON 2").grid(column=40, row=130, sticky=W)
 
def crearCliente():
    crearCliente1 = "INSERT INTO test(id,name,email) VALUES ('5','prueba','prueba')"
 
    ttk.Label(mainframe, text="Haz creado un cliente").grid(column=40, row=150, sticky=W)
 
 
####### VENTANA Tkinter #######
 
root = Tk()
root.title("Mostrar datos")
root.geometry("400x400")
 
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
 
 
ttk.Label(mainframe, text=results).grid(column=3, row=2, sticky=W)
ttk.Label(mainframe, text="Probando Label").grid(column=30, row=20, sticky=W)
 
ttk.Button(mainframe, text="BOTON", command=crearCliente).grid(column=40, row=40, sticky=W)
 
 
 
root.mainloop()

Y el archivo conexión.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import pymysql
 
# Abre conexion con la base de datos
db = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             database='test',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
##################################################
cursor = db.cursor()
 
# Seleccionador base de datos
sql = "SELECT name FROM test WHERE id = 2"
 
# Ejecutar comando
cursor.execute(sql)
 
# Mostrar
results = cursor.fetchall()
 
# Desconexion
db.close()

Tengo esto, y funciona bien hasta el sentido de que tengo importado el archivo de conexión en el main (archivo principal) lo cual tengo una variable llamada "results" que se muestra perfectamente en el main, y eso que Estrellas declarada en el archivo conexión.

Y ahora estoy intentado crear una consulta a la base de datos en la función CrearCliente de añadir un nuevo dato y no se me añade. No me da ningún error ni nada pero no se crea los datos en la base de datos. ¿que estoy haciendo mal?

Cualquier información adicional lo agradeceria.

Saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder