martes, 22 de mayo de 2018

Proyecto - Administración de Bases de Datos

Código de la Interfaz y conexión a la base de datos desde Python


       
# -*- coding: utf-8 -*-
import MySQLdb
from tkinter import *
import tkinter.messagebox
from tkinter import ttk

def conectar():
    try:
        global db
        global cur
        db = MySQLdb.connect(host='localhost', password='chocopizza', user='root', db='escuela')
        cur = db.cursor()
        print ("Conexion Correcta")
    except MySQLdb.Error as err:
        print ("MySQL Error: %s" % str(err))

def cerrarS():
    if not db.open:
        print("Cierre incorrecto")
        db.close()
    else:
        print("Cierre Correcto")

def AlDobleClick(a):
    try:
        item = ListaPrincipal.selection()
        borrar(ListaPrincipal.item(item)['values'][0])
    except IndexError as err:
        print("Error de variables: %s" % str(err))

def BorrarCampos():
    EntryNom.delete('0', 'end')
    EntryApeP.delete('0', 'end')
    EntryApeM.delete('0', 'end')
    EntryCor.delete('0', 'end')

def AlSeleccionar(a):
    global indexTupla
    BorrarCampos()
    try:
        item = ListaPrincipal.selection()
        indexTupla = ListaPrincipal.item(item)['values'][0]
        EntryNom.insert('0', ListaPrincipal.item(item)['values'][1])
        EntryApeP.insert('0', ListaPrincipal.item(item)['values'][2])
        EntryApeM.insert('0', ListaPrincipal.item(item)['values'][3])
        EntryCor.insert('0', ListaPrincipal.item(item)['values'][4])
    except IndexError as err:
        print("Error de variables: %s" % str(err))

def VenPrin():
    global VenP
    global EntryNom
    global EntryApeP
    global EntryApeM
    global EntryCor
    global ListaPrincipal
    conectar()

    VenP = Tk()
    VenP.title('Sesión de Administrador')
    VenP.geometry("600x360")
    VenP.resizable(False, False)
    VenP.configure(background='light gray')

    ListaPrincipal = ttk.Treeview(VenP)
    ListaPrincipal.grid(row=0, column=0, columnspan=5)

    ListaPrincipal["columns"] = ["num_cont", "Nombre", "Apellido_P", "Apellido_M", "Correo"]
    ListaPrincipal["show"] = "headings"
    ListaPrincipal.heading("num_cont", text="Nº de control")
    ListaPrincipal.column("num_cont", minwidth=0, width=50, stretch=NO)
    ListaPrincipal.heading("Nombre", text="Nombre")
    ListaPrincipal.column("Nombre", minwidth=0, width=150, stretch=NO)
    ListaPrincipal.heading("Apellido_P", text="Apellido Paterno")
    ListaPrincipal.column("Apellido_P", minwidth=0, width=100, stretch=NO)
    ListaPrincipal.heading("Apellido_M", text="Apellido Materno")
    ListaPrincipal.column("Apellido_M", minwidth=0, width=100, stretch=NO)
    ListaPrincipal.heading("Correo", text="Correo")
    ListaPrincipal.column("Correo", minwidth=0, width=200, stretch=NO)
    ListaPrincipal.bind("", AlDobleClick)
    ListaPrincipal.bind("<>", AlSeleccionar)

    rellenar()

    LabelNom = Label(VenP, text="Nombre: ")
    LabelNom.grid(row=1, column=1, sticky=W)
    EntryNom = Entry(VenP)
    EntryNom.grid(row=1, column=2, sticky=W)

    LabelApeP = Label(VenP, text="Apellido Paterno:")
    LabelApeP.grid(row=1, column=3, sticky=W)
    EntryApeP = Entry(VenP)
    EntryApeP.grid(row=1, column=4, sticky=W)

    LabelApeM = Label(VenP, text="Apellido Materno:")
    LabelApeM.grid(row=2, column=1, sticky=W)
    EntryApeM = Entry(VenP)
    EntryApeM.grid(row=2, column=2, sticky=W)

    LabelCor = Label(VenP, text="Correo:")
    LabelCor.grid(row=2, column=3, sticky=W)
    EntryCor = Entry(VenP)
    EntryCor.grid(row=2, column=4, sticky=W)

    Agregar = Button(VenP, text='Agregar', fg='Green', command=nuevo)
    Agregar.place(relx=0.15, rely=.85, anchor=CENTER)

    Limpiar = Button(VenP, text='Limpiar', fg='Black', command=BorrarCampos)
    Limpiar.place(relx=0.48, rely=.85, anchor=CENTER)

    Editar = Button(VenP, text='Editar', fg='Blue', command=editar)
    Editar.place(relx=0.85, rely=.85, anchor=CENTER)

    rmuser = Button(VenP, text='X', fg='red', command=CerrarSes, font=("Arial", 12))
    rmuser.place(relx=0.95, rely=.90, anchor=CENTER)

    VenP.mainloop()

def CerrarSes():
    cerrarS()
    VenP.destroy()

def rellenar():
    for i in ListaPrincipal.get_children():
        ListaPrincipal.delete(i)

    cur.execute("SELECT * FROM alumnos")
    index = iid = 0
    for row in cur.fetchall():
        ListaPrincipal.insert("", iid, index, values=row)
        index = iid = index + 1  # Contador de columnas

def LlamarProcc(dat):
    cur.callproc('alumnosx', dat)
    db.commit()

def ErrorProc():
    db.rollback()
    tkinter.messagebox.showinfo("Error al conectar", "El procedimiento ha fallado")

def nuevo():
    Nom=EntryNom.get()
    ApeP=EntryApeP.get()
    ApeM=EntryApeM.get()
    Cor=EntryCor.get()
    if len(Nom) != 0 or len (ApeP) != 0 or len(ApeM) != 0:
        cur.execute("SELECT num_cont FROM alumnos ORDER BY num_cont DESC LIMIT 1")
        try:
            VarT = ((cur.fetchone()[0]) + 1)
        except TypeError:
            VarT = 0
        Num = int(VarT)

        Datos = [Num, Nom, ApeP, ApeM, Cor, 'nuevo']
        try:
            LlamarProcc(Datos)
        except:
            ErrorProc()

        rellenar()
    else:
        tkinter.messagebox.showinfo("No ingresaste datos", "Por favor, escribe los datos a guardar")

def borrar(ID):
    result = tkinter.messagebox.askquestion("Se borrará el registro", "¿Estás seguro?", icon='warning')
    if result == 'yes':
        Datos = [ID, EntryNom, EntryApeP, EntryApeM, EntryCor, 'eliminar']
        try:
            LlamarProcc(Datos)
        except:
            ErrorProc()
    rellenar()

def editar():
    Nom = EntryNom.get()
    ApeP = EntryApeP.get()
    ApeM = EntryApeM.get()
    Cor = EntryCor.get()
    Datos = [indexTupla, Nom, ApeP, ApeM, Cor, 'editar']
    try:
        LlamarProcc(Datos)
    except:
        ErrorProc()
    rellenar()

VenPrin()

       


Proyecto y base de datos:

https://mega.nz/#!l48FxLKR!tHLPUsGIdsWtHmD4IFK8jiXugFgTIjxbpp39N6Iptf8

No hay comentarios.:

Publicar un comentario

Exposiciones - Lenguajes de interfaz

Equipo # 1 - Programación del puerto paralelo Un puerto paralelo es una interfaz entre un computador y un periférico, cuya principal carac...