Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sqlite3 database problem
#1
Hi! In general im new with python. I'm making my first tkinter app, but for some reason im not able to insert entry into the database.

I wanted to insert manually,
con.execute("INSERT INTO contacts (contact_name, contact_surname) VALUES ('Maryan', 'Maryan', '[email protected]', '2151245123','Maryan');")
but I'm getting the following error:
sqlite3.OperationalError: no such table: contacts. The database.db file it is in the same directory with the other py files. What could be the problem? Angel I will appreciate any help, thank you!


from sqlite3.dbapi2 import connect
from tkinter import messagebox
from tkinter import *
import sqlite3

con = sqlite3.connect('database.db')
cur = con.cursor()


class AddPeople(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)
        self.geometry('650x750+550+200')
        self.title('Add Contact')
        self.resizable(False, False)

        
        # Frames
        self.top = Frame(self, height = 150, bg = 'white')
        self.top.pack(fill = X)
        self.bottomFrame = Frame(self, height = 500, bg = '#adff2f')
        self.bottomFrame.pack(fill = X)

        # Heading, image and date - TOP frame
        self.top_image = PhotoImage(file = 'addressbook/icons/addperson.png')
        self.top_image_lbl = Label(self.top, image = self.top_image, bg = 'white')
        self.top_image_lbl.place(x = 120, y = 10)
        self.heading = Label(self.top, text = 'New Contact', font = 'Helvetica 15 bold', fg = '#FFA500', bg = 'white')
        self.heading.place(x = 260, y = 60)


        ### Labels and Entries ###

        # Name
        self.lbl_name = Label(self.bottomFrame, text = 'Name', font = 'Helvetica 15 bold', fg = 'white', bg = '#adff2f')
        self.lbl_name.place(x = 40, y = 40)
        self.ent_name = Entry(self.bottomFrame, width = 30, bd = 2)
        self.ent_name.insert(0, '')
        self.ent_name.place(x = 150, y = 45)

        # Surname
        self.lbl_surname = Label(self.bottomFrame, text = 'Surname', font = 'Helvetica 15 bold', fg = 'white', bg = '#adff2f')
        self.lbl_surname.place(x = 40, y = 80)
        self.ent_surname = Entry(self.bottomFrame, width = 30, bd = 2)
        self.ent_surname.insert(0, '')
        self.ent_surname.place(x = 150, y = 85)

        # Email
        self.lbl_email = Label(self.bottomFrame, text = 'Email', font = 'Helvetica 15 bold', fg = 'white', bg = '#adff2f')
        self.lbl_email.place(x = 40, y = 120)
        self.ent_email = Entry(self.bottomFrame, width = 30, bd = 2)
        self.ent_email.insert(0, '')
        self.ent_email.place(x = 150, y = 125)


        # Phone
        self.lbl_phone = Label(self.bottomFrame, text = 'Phone', font = 'Helvetica 15 bold', fg = 'white', bg = '#adff2f')
        self.lbl_phone.place(x = 40, y = 160)
        self.ent_phone = Entry(self.bottomFrame, width = 30, bd = 2)
        self.ent_phone.insert(0, '')
        self.ent_phone.place(x = 150, y = 165)

        # Address
        self.lbl_address = Label(self.bottomFrame, text = 'Address', font = 'Helvetica 15 bold', fg = 'white', bg = '#adff2f')
        self.lbl_address.place(x = 40, y = 300)
        self.address = Text(self.bottomFrame, width = 23, height = 15, wrap = WORD)
        self.address.place(x = 150, y = 200)

        # Button
        button = Button(self.bottomFrame, text = 'Add Contact', command = self.addPerson)
        button.place(x = 270, y = 460)
        self.lift()

    def addPerson(self):
        name = self.ent_name.get()
        surname = self.ent_surname.get()
        email = self.ent_email.get()
        phone = self.ent_phone.get()
        address = self.address.get(1.0, 'end-1c')

# Database query
        if (name and surname and email and phone and address != ""):
            try:
                query = "INSERT INTO contacts (contact_name, contact_surname, contact_email, contact_phone, contact_address) VALUES(?, ?, ?, ?, ?)"
                cur.execute(query, (name, surname, email, phone, address))
                con.commit()
                con.close()
                messagebox.showinfo('Success', 'Sucessfully added into the database', icon = 'info')
            except:
                messagebox.showerror('Error', 'Can Not be added to the database!', icon = 'warning')
        else:
            messagebox.showerror('Error', 'The fields are empty!', icon = 'warning')
screenshot
[Image: sc1.png]

UPDATE:

It seems my VisualStudioCode or Python doesn't want to execute query to the database.

I run the test bellow, it will create database.db and tables, but WONT insert any query. I run the command directly in 'DB Browser for SQLITE' it runs ok and insert data, what should I do?

import sqlite3

db = sqlite3.connect('database.db')
cur = db.cursor()
#cur.execute("CREATE TABLE contacts (name TEXT, surname TEXT, email TEXT, phone TEXT, address TEXT)")
cur.execute("INSERT INTO contacts(name, surname, email, phone, address) VALUES ('Example', 'example', '[email protected]','123456789', 'example st.')")

db.commit
Reply
#2
VSCode has nothing to do with inserting into database, it's only an IDE. You can install an extension (there are several) but this is not your problem.

The error that you are receiving tells all.
You have not created the table contacts.

create the table and try again. (you have the create statement commented out.

**NOTE** if you add if not exists you won't have to comment out the create statement
cur.execute("CREATE TABLE IF NOT EXISTS contacts (name TEXT, surname TEXT, email TEXT, phone TEXT, address TEXT)")

Also, as you learn more about using database, you should use placeholders for values, see: https://docs.python.org/3.8/library/sqlite3.html
Reply
#3
The code you post is different from the one that is in the screenshot. But I guess the problem is the same.

Note that your code does not create tables. You rely to work with existing database.db file. In the screenshot you get error that no table contacts exists. You show in a sqlite viewer that such table exists in some database.db file. However you should know that con = sqlite3.connect('database.db') will create empty file if it does not exists in the location.
Looking at the screenshot your current working directory is Python Tkinter Master Class. The database.db from the screenshot (where contacts table exists) is at different location Python Tkinter Master Class\Adressbook\. So you actually work with file located in Python Tkinter Master Class folder in which currently there are no tables at all.
The best would be to pass full path to sqlite3.connect() so that you are sure to work with expected database no matter where from or how you execute the code.

Also don't use all catching except, or at least don't use misleading error message - Can Not be added to the database! does not help resolve te problem if there is a problem.
Also I would like to comment on following line
if (name and surname and email and phone and address != ""):
I don't know if you did it by purpose or is sign of misunderstanding with regards to how it will be evaluated.
First late say that the brackets are redundannt
next, it's equivalent to
if (name) and (surname) and (email) and (phone) and (address != ""): # brackets here are just to explain better my point - they ar enot needed
This will work as expected if any of name, surname, email and phone are empty string, but what if you have not empty string but space in all of them and some non-empty address. In this case each of them will be evluated True and condition will pass (non-empty string is evaluated True).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create SQLite3 database with peewee Jim53_1980 2 652 Dec-20-2023, 02:38 PM
Last Post: buran
  Regex replace in SQLite3 database WJSwan 1 785 Dec-04-2023, 05:55 PM
Last Post: Larz60+
  Rows not adding to sqlite3 database using SQLAlchemy Calab 11 1,641 Jun-02-2023, 05:53 PM
Last Post: bowlofred
  Basic SQL query using Py: Inserting or querying sqlite3 database not returning data marlonbown 3 1,350 Nov-08-2022, 07:16 PM
Last Post: marlonbown
  Problem With Database Calls and Load Timbo03 1 2,118 Nov-21-2021, 10:48 AM
Last Post: Timbo03
  Python Variables and Sqlite3 Database Staples200 1 3,139 May-25-2021, 02:40 AM
Last Post: Staples200
  Problem updating value in MySQL database dangermaus33 1 1,615 Nov-24-2020, 08:32 PM
Last Post: dangermaus33
  sqlite3 database does not save data across restarting the program SheeppOSU 1 3,439 Jul-24-2020, 05:53 AM
Last Post: SheeppOSU
  ZIP file in Sqlite3 database chesschaser 4 3,459 Jul-23-2020, 09:53 PM
Last Post: chesschaser
  Telegram bot - Problem with database NoNameoN 1 1,644 Jul-13-2020, 06:39 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020