Why is my Sqlite databese not working in python? - python

I've been working on a password vault the past few days. Everything works fine, but my database doesn't work. The database is created but it doesn't store the email-adresses, usernames and passwords. Anybody knows what's wrong with my code? Code below.
Also this is the error I get everytime:
label = Label(window, text=(array[i][1]), font=("Helvetica", 12))
IndexError: list index out of range
#Databese Code
with sqlite3.connect("password_vault.db") as db:
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS masterpassword(
id INTEGER PRIMARY KEY,
password TEXT NOT NULL
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS vault(
id INTEGER PRIMARY KEY,
website TEXT NOT NULL,
username TEXT NOT NULL,
password TEXT NOT NULL
)
""")
def passwordVault():
for widget in window.winfo_children():
widget.destroy()
def addEntry():
text1 = "Website"
text2 = "Username"
text3 = "Password"
website = popUp(text1)
username = popUp(text2)
password = popUp(text3)
insert_fields = """INSERT INTO vault(website,username,password)
VALUES(?, ?, ?)"""
cursor.execute(insert_fields, (website, username, password))
db.commit
passwordVault()
cursor.execute("SELECT * FROM vault")
if (cursor.fetchall() != None):
i = 0
while True:
cursor.execute("SELECT * FROM vault")
array = cursor.fetchall()
label = Label(window, text=(array[i][1]), font=("Helvetica", 12))
label.grid(column=0, row=i+3)
label = Label(window, text=(array[i][2]), font=("Helvetica", 12))
label.grid(column=1, row=i+3)
label = Label(window, text=(array[i][3]), font=("Helvetica", 12))
label.grid(column=2, row=i+3)
btn = Button(window, text="Delete", command= partial(removeEntry, array[i][0]))
btn.grid(column=3, row=i+3, pady=10)
i += 1
cursor.execute("SELECT * FROM vault")
if (len(cursor.fetchall()) <= i):
break

It may be as simple as the fact you are using colons, not semi-colons to end your script. Python uses Semi-colons to end all functions. Not to mention, it appears there is no command for actually having those passwords, I.E. those passwords are not in your code to be accessed, as well as there is no function for the email addresses, of which you will also have to insert manually. Let me know if you need anything else.

Related

Python Tkinter text entry box to insert data to SQL Server

I have created a small python tkinter program designed to have a user write data into text entry boxes in the app then insert this data into a MS SQL server database. When clicking the insert button I am getting the following error message, stopping the app from insert the code into SQL.
cursor.execute("INSERT INTO TEST_DISA_MAIN_TABLE VALUES (:DENSITY_VALUE, :DATE, :TIME, :CHART_VALUE)",
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')*
This is my code for the python insert function:
def insertvalue():
# Create a database or connect to one
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MON-SQL-02;'
'Database=ENVIRONMENTAL;'
'Trusted_Connection=yes;')
# Create cursor
cursor = conn.cursor()
# Insert into table
cursor.execute("INSERT INTO TEST_DISA_MAIN_TABLE VALUES (:DENSITY_VALUE, :DATE, :TIME, :CHART_VALUE)",
{
'DENSITY_VALUE': DENSITY_VALUE.get(),
'DATE': DATE.get(),
'TIME': TIME.get(),
'CHART_VALUE': CHART_VALUE.get(),
})
# Commit changes
conn.commit()
#Close Connection
conn.close()
# Clear the text boxes
DENSITY_VALUE.delete(0, END)
DATE.delete(0, END)
TIME.delete(0, END)
CHART_VALUE.delete(0, END)
#Create text boxes
DENSITY_VALUE = Entry(root, width=30)
DENSITY_VALUE.grid(row=2, column=1)
DATE = Entry(root, width=30)
DATE.grid(row=3, column=1)
TIME = Entry(root, width=30)
TIME.grid(row=4, column=1)
CHART_VALUE = Entry(root, width=30)
CHART_VALUE.grid(row=5, column=1)
#Create Text box labels
DENSITY_VALUE_Label = Label(root, text="Density Value")
DENSITY_VALUE_Label.grid(row=2, column=0)
DATE_Label = Label(root, text="Date")
DATE_Label.grid(row=3, column=0)
TIME_Label = Label(root, text="Time")
TIME_Label.grid(row=4, column=0)
CHART_VALUE_Label = Label(root, text="Chart Value")
CHART_VALUE_Label.grid(row=5, column=0)
button = Button(root, text = "Show All Values", command = showvalues)
button.grid(row=0, column=0)
button = Button(root, text = "Insert Values", command = insertvalue)
button.grid(row=1, column=0)
#Commit changes
conn.commit()
# Close connection
conn.close()
root.mainloop()
I used this format to insert data into a sqlite3 db, but the same format is not working when inserting into a SQL Server database. I have tested the connection to the SQL server and can display values in the app so that part works correctly.

Tkinter get partial input from Entry box

I am new to Tkinter in Python and I am using it to build a UI for work purposes.
The UI will allow you to search through a list of businesses in a database by either a retailer ID (Integer), retailer name or username.
I have tried searching online and spent ages trying to find what I am looking for on Stackoverflow but can't find what I need.
What I am really struggling with is being able to search by partial strings in the search box and the results to display in a list box. The code below allows me to return a list of businesses but only if I type the EXACT name of the business as it appears in the database.
What I am trying to achieve is, say that there are 2 retailers in the database (these are just examples obviously):
"Market"
"Supermarket"
If I type "Market" in the entry box, I expect to see both of these in the list box. If I type "Super" or "Supermarket", I expect to see only the "Supermarket" retailer name I also don't want this to be case sensitive.
I will then want to be able to select a business from the results and perform some other tasks like sending out automatic emails.
I have access to a MySQL server database.
Here is the code:
# Search businesses
def search_now():
selected = drop.get()
sql = ""
if selected == "Search by...":
searched_label.config(text="You forgot to pick an option!")
if selected == "Business Name":
sql = "SELECT Retailer, Retailer_Name, Account_ID, Password FROM Retailers WHERE Retailer_Name like ?"
searched_label.config(text="Business(s):")
if selected == "Business ID":
sql = "SELECT Retailer, Retailer_Name, Account_ID, Password FROM Retailers WHERE Retailer like ?"
searched_label.config(text="Business(s):")
if selected == "Username":
sql = "SELECT Retailer, Retailer_Name, Account_ID, Password FROM Retailers WHERE Account_ID like ?"
searched_label.config(text="Business(s):")
searched = search_box.get()
#sql = "SELECT Retailer, Retailer_Name, Account_ID, Password FROM Retailers WHERE Retailer_Name like ?"
name = (f'%{searched}%', )
businesses = c.execute(sql, name)
businesses = c.fetchall()
#Clear the listbox
my_list.delete(0, END)
if not businesses:
searched_label.config(text="Business not found")
else:
for business in businesses:
my_list.insert(0, str(business[0]) + " " + business[1] + " " + business[2])
# Entry box to search businesses
search_box = Entry(root)
search_box.grid(row=1, column=1, padx=10, pady=10)
# Entry box label search businesses
search_box_label = Label(root, text="Enter Business name:")
search_box_label.grid(row=1, column=0, padx=1, pady=10)
# Entry box search button for businesses
search_button = Button(root, text="Search", command=search_now)
search_button.grid(row=1, column=4, padx=10, pady=10)
# Drop down box
drop = ttk.Combobox(root, value=["Search by...", "Business Name", "Business ID", "Username"])
drop.current(0)
drop.grid(row=1, column=2)
# Create searched result label
searched_label = Label(root, text="")
searched_label.grid(row=2, column=0, sticky=W, columnspan=2)
# Create a table
title_label = Label(root, text="CRM", font=("Helvetica", 16))
title_label.grid(row=0, column=0, columnspan=2, sticky=W, pady=10)
# Create a listbox
my_list = Listbox(root, width=50)
my_list.grid(row=10, column=0, columnspan=3, sticky=W, pady=10, padx=10)
root.mainloop()
I hope all this information helps!
This is now fixed! The issue was with the way I was searching for a string in the entry box. I needed to use the "f-string" string formatting feature.
Previous error code:
searched = search_box.get()
name = (searched, )
Correct code
searched = search_box.get()
name = (f'%{searched}%', )

How to insert and bind pictures in my CRUD form with Tkinter?

I'm working with Tkinter and I have a CRUD form to isert information to my SQLite database as well display them in another treeview frame, it works pretty good, but I was thinking about to isert an 'upload picture' button and a small frame for the picture near my CRUD options, I have no idea how to do it, in fact that picture must be binded to my ID code entry, in order to work also with my CRUD buttons, and have different pictures for different ID numbers. Thanks guys
UPDATE:
My CRUD code is long, basically I've got this scheme:
frame_registres = Frame(top, width=840, height=460)
frame_registres.place(x=350, y=220)
lbl_idcard = Label(frame_registres, text='ID card', font='arial 13 bold', bg='black', fg='gray')
lbl_idcard.place(x=60, y=116)
myid = StringVar()
idcard_entry = Entry(frame_registros, font='arial 12', justify='center', relief='sunken', bd=3, textvariable=myid)
idcard_entry.place(x=130, y=108, width='160', height='30')
btn_get = Button(frame_registros)
btn_add = Button(frame_registros)
btn_update = Button(frame_registros)
btn_delete = Button(frame_registros)
def get():
def add():
def update():
def delete():
UPDATE 2
from tkinter import *
import sqlite3
top = Tk()
top.configure(width='444', heigh='400')
conn = sqlite3.connect('test.db')
c = conn.cursor()
def enterdata():
id = 'hello'
photo = convert_pic()
c.execute('INSERT INTO test (id, photo) VALUES (?, ?)', (id, photo))
conn.commit()
def convert_pic():
filename = 'images/image6.jpg'
with open(filename, 'rb') as file:
photo = file.read()
return photo
btn = Button(top, text='save photo', command=enterdata())
btn.place(x='100', y='111')
mainloop()

How to give Sqlite3 table name from a variable in Python

I'm in a dilemma as to how to give my table name depending on my Combobox selections. I am using PyQt5. I tried it this way but got not the thing right.
b = self.combo.currentText()
sql = '''CREATE TABLE IF NOT EXISTS d (id int, grade text)''')
This creates a database with b as the name instead of the choice from the combobox.
You have to bind the event based on combobox selection using application_cb.bind("<>", createTable) where you have to pass function name
application_label = Label(cbFrameRow1Col2, text='Application', bg='gray46', fg='white', font=("calibri", 10))
application_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)
application_cb = ttk.Combobox(cbFrameRow1Col2, values=application_list, width=15)
application_cb.grid(row=0, column=1, sticky='w', padx=10, pady=5)
application_cb.bind("<<ComboboxSelected>>", createdb)
And now you have to call create table function when this event is triggered
def createTable(event):
tablename = application_cb.get()
conn = sqlite3.connect('temp.db')
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, Name TEXT)" % (tablename))
conn.commit()
conn.close()

Inserting user and password with SQLITE/PYTHON

Working on a group program that has users and passwords. We are trying to insert our users and passwords via python to sqlite. But atm we are only sending blank data before our graphic window pops up with a button that is supposed to send the data. We have tried different variations found on multiple websites but nothing seems to work.
from tkinter import *
import sqlite3
import sys
conn = sqlite3.connect('indexCards.db')
cur = conn.cursor()
users ={}
def addUser(entUsername, entPassword):
#global entUsername, entPassword
NAME = entUsername.get()
PASSWORD = entPassword.get()
print("add User") #this is testing only
print(NAME, PASSWORD) # this is testing to see the passed variable
//
//This is where we are having the issues
conn.executemany('INSERT INTO USER(NAME,PASSWORD)\
VALUES (? ,?);', [(NAME,PASSWORD)])
conn.commit();
return (NAME, PASSWORD)
def makeWindow():
global entUsername, entPassword
window = Tk()
window.title('Add New User')
lblInst = Label(window, text = "Create your account here:", font=("Helvetica",16))
lblInst.pack()
lblUsername = Label(window, text="Please enter a username: ")
entUsername = Entry(window)
lblUsername.pack()
entUsername.pack()
lblPassword = Label(window, text="Please enter a password: ")
entPassword = Entry(window)
lblPassword.pack()
entPassword.pack()
btn = Button(window, text="Create", command=addUser(entUsername, entPassword))
btn.pack()
print (addUser(entUsername, entPassword))
print('entUsername', 'entPassword')
#window.mainloop()
return window
#if __name__ == '__main__':
# main():
window = makeWindow()
window.mainloop()
The problem is that you're calling the function immediately, before the user has a chance to enter any data.
See Why is Button parameter “command” executed when declared?
The reason it invokes the method immediately and pressing the button does nothing is that addUser(entUsername, entPassword) is evaluated and its return value is attributed as the command for the button. So if addUser prints something to tell you it has run and returns None, you just run addUser to evaluate its return value and given None as the command for the button.
To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:
import sqlite3
from tkinter import *
conn = sqlite3.connect('indexCards.db')
cur = conn.cursor()
users = {}
cur = conn.cursor()
cur.execute('''
Create table if not exists USER(NAME varchar(100), PASSWORD varchar(100))
''')
def addUser():
NAME = entUsername.get()
PASSWORD = entPassword.get()
print("add User") # this is testing only
print(NAME, PASSWORD) # this is testing to see the passed variable
# This is where we are having the issues
conn.executemany('INSERT INTO USER(NAME,PASSWORD) VALUES (? ,?);', [(NAME, PASSWORD)])
conn.commit()
return (NAME, PASSWORD)
def makeWindow():
global entUsername
global entPassword
window = Tk()
window.title('Add New User')
lblInst = Label(window, text="Create your account here:", font=("Helvetica", 16))
lblInst.pack()
lblUsername = Label(window, text="Please enter a username: ")
entUsername = Entry(window)
lblUsername.pack()
entUsername.pack()
lblPassword = Label(window, text="Please enter a password: ")
entPassword = Entry(window)
lblPassword.pack()
entPassword.pack()
btn = Button(window, text="Create", command=addUser)
btn.pack()
print(addUser())
window.mainloop()
return window
window = makeWindow()
If you don't want to create global then you can pass the function with multiple arguments to an anonymous function i.e lambda function
btn = Button(window, text="Create", command= lambda : addUser(entUsername, entPassword))

Categories

Resources