Python - sqlite3.OperationalError: no such table: cliente

 
Vista:
sin imagen de perfil
Val: 7
Ha aumentado su posición en 131 puestos en Python (en relación al último mes)
Gráfica de Python

sqlite3.OperationalError: no such table: cliente

Publicado por Cristian Felipe (6 intervenciones) el 12/06/2021 05:18:59
Estoy practicando hacer un CRUD, pero al momento de crear el usuario me arroja un error y no entiendo que esta mal en la función crear, tenía un try except y lo elimine para saber cual era el error y me dice

File "C:\BeeDevApp\CRUD_CLIENTES.py", line 232, in crear
self.cursor.execute("INSERT INTO cliente VALUES (NULL,?,?,?,?,?)", (self.datos))
sqlite3.OperationalError: no such table: cliente

No entiendo que sucede, a continuación comparto mi codigo, les agradecería que me pudieran ayduar estoy aprendiendo python de manera autodidacta y bueno no tengo algún tutor, la comunidad es la ayuda mas cercana que tengo muchas gracias. Apenas estor empezado a entender este lenguaje

Codigo:

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""CRUD APLICACIÓN FOR BEE DEV"""
 
"""
IMPORTAMOS LAS RESPECTIVAS BIBLIOTECAS QUE SE NECESITARAN EN MI APLICACIÓN CRUD
"""
from tkinter import ttk
from tkinter import *
import tkinter as tk
import sqlite3
from tkinter import messagebox
 
 
class Crud:
 
    ########################  GRAFIC CONSTRUCCIÓN OF THE WINDOW  ############################
    def __init__(self, window):
 
        self.ventana = window
        self.ventana.title("BEE DEV CRUD CLIENT DATABASE")
        self.ventana.iconbitmap("Iconos/new_users.ico")
        self.ventana.resizable(0, 0)
 
        ############################ CREACIÓN INTERFAZ GRÁFICA DE LA TABLA ###################
        self.tree = ttk.Treeview(self.ventana, height=10, columns=("#0", "#1", "#2", "#3", "#4"))
        # lA COLUMNA DE ITEM YA ESTÁ ESTABLECIDA
        self.tree.heading("#0", text="Item", anchor=CENTER)
        self.tree.heading("#1", text="Nombre", anchor=CENTER)
        self.tree.heading("#2", text="Apellido", anchor=CENTER)
        self.tree.heading("#3", text="ID", anchor=CENTER)
        self.tree.heading("#4", text="User", anchor=CENTER)
        self.tree.heading("#5", text="Password", anchor=CENTER)
        self.tree.grid(row=2, column=0)
 
        # Modificación del ancho de las celdas
        self.tree.column("#0", width=100)
        self.tree.column("#4", width=100)
        self.tree.column("#5", width=100)
 
        ##Creando la barra de menus
        self.contador = 0
        self.menu_barr = tk.Menu(self.ventana)
        self.m_inicio = tk.Menu(self.menu_barr, tearoff=0)
        self.m_inicio.add_command(label="Conectar", command=self.conexion)
        self.m_inicio.add_command(label="Crear", command=self.ventana_top_crud)
        self.m_inicio.add_command(label="Borrar base de datos", command=self.all_delete)
        self.m_inicio.add_command(label="Mostrar datos", command=self.mostrar)
        self.m_inicio.add_separator()
        self.m_inicio.add_command(label="salir", command=self.salir)
        self.menu_barr.add_cascade(label="Inicio", menu=self.m_inicio)
 
        self.ayudamenu = tk.Menu(self.menu_barr, tearoff=0)
        self.ayudamenu.add_command(label="Acerca de", command="")
        self.menu_barr.add_cascade(label="Ayuda", menu=self.ayudamenu)  # Añadimos a la barra principal
 
        self.ventana.config(menu=self.menu_barr)
 
        ############################### VARIABLES OF MY CLIENT TABLE ##########################
        self.item = IntVar()
        self.name_user = StringVar()
        self.last_name_user = StringVar()
        self.id_user = IntVar()
        self._user = StringVar()
        self._pass = StringVar()
 
    ########################## DESPLIEGUE DE LA VENTANA DE REGISTRO ##############################
 
    def ventana_top_crud(self):
        self.contador = self.contador + 1
        if self.contador == 1:
            global raiz
            ###### Entorno gráfico ####################
            self.ventana2 = Toplevel(raiz)
            self.ventana2.title("Registro nuevos usuarios")
            self.ventana2.resizable(0, 0)
            self.ventana2.iconbitmap("Iconos/new_users.ico")
 
            ######## Contenedor #################3
 
            self.label_frame = ttk.Labelframe(self.ventana2, text="Configuración/Registros clientes")
            self.label_frame.grid(row=0, column=0, padx=10, pady=10)
 
            ########################## LABELS ####################################################
            self.label_item = ttk.Label(self.label_frame, text="Item")
            self.label_item.grid(row=0, column=0, padx=10, pady=10)
 
            self.label_ID = ttk.Label(self.label_frame, text="ID")
            self.label_ID.grid(row=1, column=0, padx=10, pady=10)
 
            self.label_name = ttk.Label(self.label_frame, text="Nombre")
            self.label_name.grid(row=2, column=0, padx=10, pady=10)
 
            self.label_lastname = ttk.Label(self.label_frame, text="Apellido")
            self.label_lastname.grid(row=3, column=0, padx=10, pady=10)
 
            self.label_user = ttk.Label(self.label_frame, text="Usuario")
            self.label_user.grid(row=4, column=0, padx=10, pady=10)
 
            self.label_pss = ttk.Label(self.label_frame, text="Contraseña")
            self.label_pss.grid(row=5, column=0, padx=10, pady=10)
 
            ################# CAJAS DE TEXTO #################################
            self.e_item = ttk.Entry(self.label_frame, textvariable=self.item, state="readonly")
            self.e_item.grid(row=0, column=2)
 
            self.e_id = ttk.Entry(self.label_frame, textvariable=self.id_user)
            self.e_id.grid(row=1, column=2, padx=10, pady=10)
            self.e_id.focus()
 
            self.e_name = ttk.Entry(self.label_frame, textvariable=self.name_user)
            self.e_name.grid(row=2, column=2, padx=10, pady=10)
 
            self.e_lastname = ttk.Entry(self.label_frame, textvariable=self.last_name_user)
            self.e_lastname.grid(row=3, column=2, padx=10, pady=10)
 
            self.e_user = ttk.Entry(self.label_frame, textvariable=self._user)
            self.e_user.grid(row=4, column=2, padx=10, pady=10)
 
            self.e_pass = ttk.Entry(self.label_frame, textvariable=self._pass)
            self.e_pass.grid(row=5, column=2, padx=10, pady=10)
 
            ####### CREAMOS LOS BOTONES ###############
            # ---------------------------------------------------------------------------##
            self.s = ttk.Style()
            self.s.configure("Peligro.TButton", foreground="#ff0000")
            ## -------------------------------------------------------------------------##
 
            self.crear_boton = ttk.Button(self.label_frame, text="Crear", command=self.crear)
            self.crear_boton.grid(row=6, column=2, sticky="we")
            self.s = ttk.Style()
            self.borrar_boton = ttk.Button(self.label_frame, text="Borrar Registro"
                                           , command=self.borrar, style="Peligro.TButton")
 
            self.borrar_boton.grid(row=7, column=2, sticky="we")
 
            self.actualizar_boton = ttk.Button(self.label_frame, text="Actualizar", command=self.update)
            self.actualizar_boton.grid(row=6, column=0, sticky="we")
 
            self.ventana2.wait_window()
            self.contador = 0
        else:
            pass
 
    ##############################_CONECTAR A LA BASE DE DATOS ###########################################
 
    def conexion(self):
        # Creamos las variables y las hacemos atributos de los objetos
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
        """
        Creamos un try except por si se vuelve a conectar y ya esta creado
        no se nos caiga el sistema
        """
        try:
 
            # Creamos nuestra primera tabla Definimos los columnas de nuestra tabla
 
            self.cursor.execute("""
            CREATE TABLE cliente(
            Item INTEGER PRIMARY KEY AUTOINCREMENT,
            Nombre VARCHAR (150) NOT NULL,
            Apellido (150) NOT NULL,
            ID INT NOT NULL,
            User VARCHAR (15) NOT NULL,
            Contraseña VARCHAR (16) NOT NULL
            )
            """)
 
            messagebox.showinfo("Estado de creación", """
            Base de datos creada exitosamente
            """)
        except:
 
            """
            Si la tabla ya está creada, entonces
            mostrará que la conexión a la tabla ha sido
            exitosa
            """
 
            messagebox.showinfo("""
            Estado de conexión
            """, """ Conexión a la base de datos exitoso""")
 
    #####################  FUNCIÓN PARA BORRAR TODA LA TABLA #############################################
 
    def all_delete(self):
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
        # Variable de validación
        variable = messagebox.askyesno(title="ADVERTENCIA"
                                       , message="Los datos se borraran definitivamente, ¿Desea Continuar?")
        try:
            # Condicional para validar la respueta del usuario
            if variable == True:
                # Borra la tabla creada
                self.cursor.execute("DROP TABLE cliente")
 
        except:
            messagebox.showerror("Error", """
            No es posible borrar la tabla
            es posible que no haya ningun elemento
            o no se haya creado""")
 
    ########################## FUNCIÓN PARA SALIR DE LA VENTANA CRUD ###########################################
    def salir(self):
        variable = messagebox.askquestion("Bee Dev", "¿Esta Seguro que desea salir")
 
        if variable == "yes":
            self.ventana.destroy()
 
    ################ PARA LIMPIAR LAS CAJAS DE TEXTO CUANDO SE HAYA INGRESADO Y REGISTRADO AL USARIO ###########
 
    def limpiar_campos(self):
 
        self.item.set("")
        self.id_user.set("")
        self.name_user.set("")
        self.last_name_user.set("")
        self._user.set("")
        self._pass.set("")
 
    ###################################################### |METODOS CRUD| #######################################
 
    def crear(self):
 
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
 
        self.datos = self.name_user.get(), self.last_name_user.get(), self.id_user.get(), self._user.get(), self._pass.get()
        self.cursor.execute("INSERT INTO cliente VALUES (NULL,?,?,?,?,?)", (self.datos))
        self.mi_conexion.commit()
 
        self.limpiar_campos()
        self.mostrar()
 
    def mostrar(self):
 
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
        self.registros = self.tree.get_children()
 
        # Borrado para la ventana
        for element in self.registros:
            self.tree.delete(element)
 
        try:
            self.cursor.execute("SELECT* FROM cliente")
 
            for fila in self.cursor:
                self.tree.insert("", 0, text=fila[0], values=(fila[1], fila[2], fila[3], fila[4], fila[5]))
 
        except:
            pass
 
    def update(self):
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
        try:
            self.datos = (self.name_user.get(), self.last_name_user.get(),
                          self.id_user, self._user.get(), self._pass.get())
 
            self.cursor.execute(f"""
            UPDATE INTO cliente SET Nombre=?, Apellido=?, ID=?,User=?,Contraseña=?
            WHERE Item = {self.item.get()}
            """, self.datos)
            self.mi_conexion.commit()
        except:
            messagebox.showwarning("Error", "Ha ocurrido un error al hacer el registro")
 
    def borrar(self):
        self.mi_conexion = sqlite3.connect("data")
        self.cursor = self.mi_conexion.cursor()
 
        try:
            respuesta = messagebox.askyesno(title="¡ADVERTENCIA!",
                                            message=f"¿Desea eliminar el registo del cliente {self.name_user} {self.last_name_user}")
            if respuesta == True:
                self.cursor.execute(f"""
                DELETE FROM cliente WHERE Item = {self.item.get()}
                """)
 
        except:
 
            messagebox.showwarning(title="ERROR", message="Ocurrio un error al tratar de borrar el registro")
 
        self.limpiar_campos()
        self.mostrar()
 
 
# Condicional para inciar la aplicación
 
if __name__ == "__main__":
    # creamos la ventana que tendra el contenido grafico de la tabla
    raiz = tk.Tk()
    main_window = Crud(raiz)  # Creamos un Objeto Crud
    raiz.mainloop()  # Efectuamos el cliclo infinito mainloop
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
sin imagen de perfil

sqlite3.OperationalError: no such table: cliente

Publicado por tulsi (2 intervenciones) el 01/04/2022 15:31:33
Hola, no se si hayas podido resolver el problema, en mi caso estoy aprendiendo a hacer llaves foreanas.

Este es el codigo

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:\\Users\\Dell\\PycharmProjects\\db.testfive'
db = SQLAlchemy(app)

lenguajes_programador = db.Table('lenguajes_programador',
db.Column('lenguaje_id', db.Integer, db.ForeignKey('lenguaje.id'), primary_key=True),
db.Column('programador_id', db.Integer, db.ForeignKey('programador.id'), primary_key=True))

class Empresa(db.Model):
id = db.Column(db.Integer, primary_key=True)
nombre = db.Column(db.String(20))
fundacion = db.Column(db.Integer, nullable=True)

def __repr__(self):
return f'{self.nombre}'


class Lenguaje(db.Model):
id = db.Column(db.Integer, primary_key=True)
nombre = db.Column(db.String(60))
creador = db.Column(db.String(60))

def __repr__(self):
return f'{self.nombre}'

class Programador(db.Model):
id = db.Column(db.Integer, primary_key=True)
nombre = db.Column(db.String(30))
edad = db.Column(db.Integer)

#llave -- clave foreana

empresa_id = db.Column(db.Integer, db.ForeignKey('empresa.id'))

#relacion entre la columna y el objeto

empresa = db.relationship('Empresa', backref=db.backref('programadores', lazy=True))
lenguajes = db.relationship('Lenguaje', secondary=lenguajes_programador,
backref=db.backref('programadores', lazy=True))

def __repr__(self):
return f'{self.nombre}'

Y aqui es donde creo la base de datos y las instancias en la consola

>>> from app import *
>>> db.create_all()
>>> google = Empresa(nombre='Google', fundacion=1998)
>>> microsoft = Empresa(nombre='Microsoft', fundacion=1975)
>>> db.session.add(google)
>>> db.session.add(microsoft)
>>> java = Lenguaje(nombre='Java', creador='James Gosling')
>>> c = Lenguaje(nombre='C', creador='Dennis Ritchie')
>>> db.session.add(java)
>>> db.session.add(c)
>>> juanito = Programador(nombre='Juanito', edad=23, empresa=google)
>>> mark = Programador(nombre='Mark', edad=26, empresa=microsoft)
>>> db.session.add(mark)
>>> db.session.add(juanito)
>>> db.session.commit()

Y este es el error que me arroja a la hora de hacer el commit

(sqlite3.OperationalError) no such table: empresa
[SQL: INSERT INTO empresa (nombre, fundacion) VALUES (?, ?)]
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 7
Ha aumentado su posición en 131 puestos en Python (en relación al último mes)
Gráfica de Python

sqlite3.OperationalError: no such table: cliente

Publicado por Cristian Felipe (6 intervenciones) el 01/04/2022 16:05:34
Veo que tú error es principalment porque no has creado la tabla en sqlite3. No sé a cerca de las llaves foráneas pero sería revisar tu código bien pero por el momento eso es lo que veo cuando pueda revisar tu código me comunicaría contigo,en tus comentarios escríbeme un correo para enviarte mi respuesta
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil

sqlite3.OperationalError: no such table: cliente

Publicado por tulsi (2 intervenciones) el 01/04/2022 16:33:39
Muchas gracias por responder, checare la observación que me has dado, sólo que no se cómo enviarte un correo.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar