sqlite3/tkinter: how do I remove treeview row using rowid from database - python

from tkinter import *
import sqlite3
app = Tk()
app.geometry('1000x600')
def remove_one():
x = my_tree.selection()[0]
my_tree.delete(x)
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
rowid = c.lastrowid
c.execute("DELETE from customers WHERE rowid = ", (rowid))
conn.commit()
conn.close()
remove_one_button = Button(button_frame, text = 'Remove Record', command= remove_one)
remove_one_button.grid(row =0, column=2, padx = 10, pady = 10)
app.mainloop()
output:
sqlite3.OperationalError: incomplete input
I want to be able to delete a row from sqlite3 database using the row id that is naturally assigned to each row

The DELETE SQL statement is obviously incomplete, it should be:
c.execute("DELETE from customers WHERE rowid = ?", (rowid,))
How to get the rowid? If you insert those records into my_tree like below:
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
c.execute('SELECT rowid, * FROM customers')
for row in c:
# use `iid` option to store the rowid
my_tree.insert('', 'end', iid=row[0], values=row[1:])
conn.close()
Then you can use my_tree.selection()[0] (you already did it in remove_one()) to get the rowid of the selected row.
Below is the modified remove_one():
def remove_one():
selected = my_tree.selection()
if selected:
rowid = selected[0]
my_tree.delete(rowid)
conn = sqlite3.connect('CustomerRecords.db')
c = conn.cursor()
c.execute("DELETE from customers WHERE rowid = ?", (rowid,))
conn.commit()
conn.close()
else:
print("No record selected")

Related

Whenever I try to search for a record I am met with an error saying that the CustomerID column doesn't exist in the searchDataService function

import sqlite3
def ServiceData():
conn=sqlite3.connect("Service.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS service(id INTEGER PRIMARY KEY, CustomerID INTEGER, ServiceName text, ServicePrice text, Date text, Time text, ExtraProducts text)")
conn.commit()
conn.close()
def addServiceRec(CustomerID, ServiceName, ServicePrice, Date, Time, ExtraProducts ):
conn=sqlite3.connect("Service.db")
cur=conn.cursor()
cur.execute("INSERT INTO Service VALUES (NULL, ?,?,?,?,?,?)", (CustomerID, ServiceName, ServicePrice, Date, Time, ExtraProducts))
conn.commit()
conn.close()
def searchDataService(CustomerID):
conn=sqlite3.connect("Service.db")
cur=conn.cursor()
cur.execute("SELECT * FROM Service WHERE CustomerID=?", (CustomerID,))
rows=cur.fetchall()
conn.close()
return rows
when ran in the front-end I am told that the CustomerID column by which it searches does not exist yet it is created above this function.
ServiceData()
Error: cur.execute("SELECT * FROM Service WHERE CustomerID=?", (CustomerID,))
sqlite3.OperationalError: no such column: CustomerID
Front end
def search():
Customerlist.delete(0,END)
for rows in cusDatabase_BackEnd.searchData(ID_entry.get()):
rows = list(rows)
for i in range(len(rows)):
rows[i] = str(rows[i]).strip()
Customerlist.insert(END,rows,str(""))
CustomerID = IntVar()
label= Label(window, text="Customer's ID:", font=('arial',13,'bold'))
label.place(x=30, y=100)
ID_entry=ttk.Entry(window, textvariable = CustomerID)
ID_entry.place(x=210,y=100)
ID_entry.focus()
btnSearch2 = tk.Button(window, text="Search record", command = search)
btnSearch2.place(x=1150,y=160, width=125, height=50)

Python SQLite Select from Database

My Database
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
# c.execute('''CREATE TABLE Karteikarten
# ([Frage] text, [Antwort] text)''')
F1 = input("Frage: ") A1 = input("Antwort: ")
c.execute('INSERT INTO Karteikarten Values ( ?, ?)', (F1, A1,))
# c.execute('SELECT * FROM Karteikarten')
# print(c.fetchall())
conn.commit()
conn.close()
Now to my question. How can I take the selected input from the database and print it out? I want to compare it with an input from a user later.
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
print(DBF1)
conn.commit()
conn.close()
If all you want to do is fetch output from the database, then you'd use
foo = c.fetchone()
or
foo = c.fetchall()
to store the output from the database into a variable
You would then print(foo)
IE:
import sqlite3
conn = sqlite3.connect('Karteikarten.db')
c = conn.cursor()
c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
DBF1 = c.fetchone() # or c.fetchall()
print(DBF1)
conn.commit()
conn.close()
Just fetch your result before the print statement.
Change this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
to this:
DBF1 = c.execute('SELECT Frage FROM Karteikarten ORDER BY RANDOM() LIMIT 1').fetchall()
and print(DBF1) will give you the desired output as a list of tuples

How to fetch data from postgresql using QLineEdit text() into QtableWidgit

I'm trying to fetch data from postgreSQL using if statement into QTableWidget, however when I'm applying variable and assigning null value(none), there is nothing showing in my table. And I cannot use where clause with QlineEdit. Is there any possible way to reproduce this code so it works properly?
def LoadData(self):
name = self.Name_search.text()
conn = psycopg2.connect(
database = "postgres",
user = "postgres",
password = "**********",
host = "localhost",
port = "5432"
)
if name is None:
with conn:
cur = conn.cursor()
rows = cur.execute("Select * from swimming_pool_users where name = '%s'",(name))
data = cur.fetchall()
for row in data:
self.AddTable(row)
cur.close()
def AddTable(self,columns):
rowPosition = self.tableWidget2.rowCount()
self.tableWidget2.insertRow(rowPosition)
for i, column in enumerate(columns):
self.tableWidget2.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(str(column)))
def ClearTableData (self):
while (self.tableWidget2.rowCount() > 0):
self.tableWidget2.removeRow(0)
I really don't understand what do you want exactly, but this is an example of how to show data from postgresql database to a QtableWidgit
def exemple_Qtablewidgit(self):
connection = psycopg2.connect(user="postgres",
password="password",
host="localhost",
database="database")
self.cur = connection.cursor()
name = self.lineEdit.text()
self.cur.execute(''' SELECT * FROM exemple WHERE name =%s''', (name,))
data = self.cur.fetchall()
if data :
self.tableWidget.setRowCount(0)
self.tableWidget.insertRow(0)
for row, form in enumerate(data):
for column , item in enumerate(form):
self.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
column += 1
row_position = self.tableWidget.rowCount()
self.tableWidget_3.insertRow(row_position)

sqlite3.OperationalError: no such table: store

I'm learning sqlite3 with python, but I've been facing this error: "sqlite3.OperationalError: no such table: store". How do I get around this?
import sqlite3
def create_table(): #function to create the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(item, quantity, price ): #function to insert into the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("INSERT INTO store VALUES(?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
insert("biscuits",500,20000)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
return rows
conn.close()
print(view())
You forgot to call the create_table method before calling insert. As you haven't called the the create_table method the insert method tries to insert a record to a non existing table.
The solution is simply to call the create_table method before insert as follows:
create_table() # Add this line before the insert
insert("biscuits", 500, 20000)

How to query from sqlite3 database if content in the entry match small requirement

I want to querying data from sqlite3 db from python and populate it in a Listbox but if am doing the search i have to provide the full name like Harvard University before the records can be inserted into the Listbox.
I want to query record like Harvard University by providing only Harvard then it will output all records with Havard content in it for me because if i don't provide full name it will not populate the listbox with any record.
Your suggestions are welcome to achieve this.
import tkinter as tk
import sqlite3
conn = sqlite3.connect("STATS.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS institution(id INTEGER PRIMARY KEY,
name TEXT)")
conn.commit()
conn.close()
def query_record():
data1 = e1_search.get()
conn = sqlite3.connect("STATS.db")
cur = conn.cursor()
cur.execute("SELECT * FROM institution WHERE name=?", (data1,))
row = cur.fetchall()
for n in row:
List.insert(tk.END, n)
print(n)
conn.close()
root = tk.Tk()
root.geometry("300x300")
List = tk.Listbox(root, width=100)
List.pack()
e1_search = tk.StringVar()
e1 = tk.Entry(root, textvariable=e1_search)
e1.pack()
b = tk.Button(text="Search", command=query_record)
b.pack(side=tk.BOTTOM)
root.mainloop()
I think you may have to modify the query.
Since "SELECT * FROM institution WHERE name=?", (data1,)
will exactly match the input string you can try with,
"SELECT * FROM institution WHERE name like ?", (data1+'%',).
Hope this works!

Categories

Resources