This is the frontend of my program. This a function to delete a set of records from a table. It gives me this error:project1Database.deleteRec(sd[0])
NameError: name 'sd' is not defined. I know it probably a little mistake by I am still new to coding so anything can help.
def EmployeeRec(event):
global sd
searchEmp = employeelist.curselection()[0]
sd = employeelist.get(searchEmp)
self.txtEmpID.delete(0,END)
self.txtEmpID.insert(0,sd[1])
self.txtFirstname.delete(0,END)
self.txtFirstname.insert(END,sd[2])
self.txtMiddlename.delete(0,END)
self.txtMiddlename.insert(END,sd[3])
self.txtLastname.delete(0,END)
self.txtLastname.insert(END,sd[4])
self.txtDob.delete(0,END)
self.txtDob.insert(END,sd[5])
self.txtNationality.delete(0,END)
self.txtNationality.insert(END,sd[6])
self.txtNI.delete(0,END)
self.txtNI.insert(END,sd[7])
self.txtAddres.delete(0,END)
self.txtAddres.insert(END,sd[8])
self.txtPostcode.delete(0,END)
self.txtPostcode.insert(END,sd[9])
self.txtphonenumber.delete(0,END)
self.txtphonenumber.insert(END,sd[10])
self.txtEmail.delete(0,END)
self.txtEmail.insert(END,sd[11])
self.txtPassportnumber.delete(0,END)
self.txtPassportnumber.insert(END,sd[12])
self.txtPassportexpirydate.delete(0,END)
self.txtPassportexpirydate.insert(END,sd[13])
self.txtgender.delete(0,END)
self.txtgender.insert(END,sd[14])
def deleteData():
if(len(EmpID.get())!=0):
project1Database.deleteRec(sd[0])
clearData()
displayData()
This is the backend. This is the table for my program.
import sqlite3
#backend
def employeeData():
conn = sqlite3.connect('projectv4.db')
c= conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS employee(EmployeeID INTEGER PRIMARY KEY,EmpID text,
Firstname text,Middlename text, Lastname text,
Dob text, Nationality text, NI text, Addres text, Postcode text, phonenumber text,
Email text, Passportnumber text, Passportexpirydate text,
gender text)""")
conn.commit()
conn.close()
This is the function I am trying to call from my frontend:
def deleteRec(EmployeeID):
conn = sqlite3.connect('projectv4.db')
c= conn.cursor()
c.execute("DELETE FROM employee WHERE EmployeeID = ?", (EmployeeID,))
conn.commit()
conn.close()
deleteData refers to sd before initializing it. Assuming you mean the same global variable as in EmployeeRec, you need to explicitly state that it's global:
def deleteData():
if(len(EmpID.get())!=0):
global sd #here!
project1Database.deleteRec(sd[0])
clearData()
displayData()
Related
I am trying to select something from the database in sqlite3.
import sqlite3
conn = sqlite3.connect("db_informatii_principal.db")
c = conn.cursor()
c.execute("CREATE TABLE persoane (id integer PRIMARY KEY, nume text, prenume text, telefon text, varsta text, adresa text, inaltime text, instagram text, detalii text)")
conn.commit()
c.execute("INSERT INTO persoane VALUES(NULL, 'Mustea', 'David', '0425698333', '17', 'Exemplu Adresa 1', '182', 'george.george', 'Ii place sa bea')")
conn.commit()
lista = ["David", "Mustea"]
c.execute(f"SELECT * FROM persoane WHERE nume = '{lista[0] or lista[1]}' AND prenume = '{lista[0] or lista[1]}'")
for x in c.fetchall():
print(x)
I am using the AND operator in sqlite3 and the or operator in f-string in python, and it's giving me no results.
Your f-string is substituting the Python expression lista[0] or lista[1], which will return "David". I suspect you wanted WHERE (name = '{lista[0]}' OR name = '{lista[1]}') AND (prenume = '{lista[0]}' OR prenume = '{lista[1]}'), but there are many better ways to do this. You should NEVER handle this kind of string substitution yourself. Let the database do it. It knows the quoting rules. Your code would fail, for example, if you looked for the name "O'Shea".
c.execute("SELECT * FROM persoane WHERE name IN (?,?) AND prenume IN (?,?);", lista + lista )
I am trying to check if a class exists within a "classinfo" database and based on whether it exists or not, will add the details of the class to the database. However, I keep getting and error saying that the parameters for one of the values isnt right.
c.execute("""CREATE TABLE IF NOT EXISTS users (
UserID text PRIMARY KEY,
FName text,
SName text,
username text,
password varchar,
userType text)""")
c.execute("""CREATE TABLE IF NOT EXISTS ClassInfo (
ClassID text PRIMARY KEY,
ClassName text,
Teacher text,
FOREIGN KEY("Teacher") REFERENCES "users"("UserID"));""")
conn.commit()
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
ClassName = (var_classname.get())
c.execute("SELECT * FROM classinfo WHERE ClassName = ?", (ClassName,))
data = c.fetchall()
if len(data) == 0:
ClassID = str(uuid.uuid4()).replace('-','')
c.execute("SELECT * FROM ClassInfo WHERE ClassID = ?", (ClassID,))
bruh = c.fetchall()
if len(bruh) == 0:
var_insert_classinfo = (ClassID, var_classname, username)
c.execute('insert INTO ClassInfo (ClassID, ClassName, Teacher)VALUES(?,?,?);', var_insert_classinfo,)
conn.commit()
Label(screen6, text = "Successfully registered! Class name is "+ClassName+"", fg = "GREEN", font = ("Calibri",12)).pack()
c.execute('insert INTO ClassInfo (ClassID, ClassName, Teacher)VALUES(?,?,?);', var_insert_classinfo,)
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
I am trying to query whether the staff ID and password are correct. The query works, however I want to get the fname and lname data from the database and print certain fields. It seems as though the row[fname] and row[lname] doesn't work... is there another way to do this? I keeps saying fname is not defined.
import sqlite3
connection = sqlite3.connect('shop.db')
cursor = connection.cursor()
create_table = '''
CREATE TABLE IF NOT EXISTS employee (
staff_ID INTEGER PRIMARY KEY,
password CHAR(4),
fname VARCHAR(20),
lname VARCHAR(30));'''
cursor.execute(create_table)
staffid = input('staff id: ')
password = input('password: ')
cursor.execute('SELECT * FROM employee WHERE staff_ID=? AND password=?', [staffid, password])
row = cursor.fetchone()
if row != None:
print(row[fname]+' '+row[lname])
You may insert any values into this table, I just didn't want the code to look too bulky... Thanks!
I am using the Spyder2 IDE in the python(x,y) package. The below function runs fine in Iron Python, but has errors when I run in the console. I need it to run in the console so that I can use Pyinstaller. The error I get is: "Error binding parameter 0. Probably unsupported type." The line showing the error is the "cur.execute" line. I'm also using Sqlite3 and getting text data from PYQT4 lineEdit fields.
Here is the code:
def update_clients(self):
#Get client id from list
cid = None
try:
cid = self.client_list_id()
except:
QtGui.QMessageBox.warning(self, 'Warning', 'You must first select a client before you update')
if cid:
#Get update items
first = self.lineEdit_c_first.text()
last = self.lineEdit_c_last.text()
add1 = self.lineEdit_c_address1.text()
add2 = self.lineEdit_c_address2.text()
city = self.lineEdit_c_city.text()
state = self.lineEdit_c_state.text()
zipp = self.lineEdit_c_zip.text()
phone = self.lineEdit_c_phone.text()
cell = self.lineEdit_c_phone_cell.text()
off = self.lineEdit_c_phone_office.text()
email = self.lineEdit_c_email.text()
notes = self.textEdit_c_notes.toPlainText()
#Update database
conn = sqlite3.connect('gibbs.db')
cur = conn.cursor()
sql = ("""
UPDATE clients
SET
firstname = ?,
lastname = ?,
address1 = ?,
address2 = ?,
city = ?,
state = ?,
zip = ?,
phone = ?,
officephone = ?,
cell = ?,
email = ?,
notes = ?
WHERE rowid = ?
""")
cur.execute(sql, (first, last, add1, add2, city, state, zipp, phone, off, cell, email, notes, cid,))
conn.commit()
conn.close()
QtGui.QMessageBox.information(self, 'Success', 'Database successfully updated')
Additionally, since the issue is somehow related to data types, here is the code that I used to create the database tables:
import sqlite3
def create_connection():
try:
conn = sqlite3.connect('gibbs.db')
return conn
except:
pass
return None
def create_clients():
try:
conn = create_connection()
print conn
c = conn.cursor()
c.execute("""
CREATE TABLE clients (
id INTEGER PRIMARY KEY,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
firstname TEXT,
lastname TEXT,
address1 TEXT,
address2 TEXT,
city TEXT,
state TEXT,
zip TEXT,
phone TEXT,
officephone TEXT,
cell TEXT,
email TEXT,
notes TEXT
)
""")
conn.close()
except:
print "table already exists"
I added the line print type(first), as suggested by #roganjosh, just before the query. When running the program, the result was different in the two consoles. The Iron Python console outputs: <type 'unicode'> and in Python 2.7 console it is: <class 'PyQt4.QtCore.QString'>.
I solved by adding the str() function when getting my text from the PYQT4 lineEdits. For example:
first = str(self.lineEdit_c_first.text())
I have the following function:
def credential_check(username, password):
conn = sqlite3.connect('pythontkinter.db')
c = conn.cursor()
idvalue = c.execute('''SELECT ID FROM userdetails WHERE username = "{0}"'''.format(username)).fetchall()
print(idvalue)
I wish to assign the value of ID in my userdetails table to the variable idvalue in the row where the inputted username = userdetails username, however when I use this fetchall() I get [('0',)] printed out rather than just 0.
How do I go about doing this?
Thanks
You can use fetchone() if you only want one value. However, the result will still be returned as a tuple, just without the list.
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS testing(id TEXT)''')
conn.commit()
c.execute("""INSERT INTO testing (id) VALUES ('0')""")
conn.commit()
c.execute("""SELECT id FROM testing""")
data = c.fetchone()
print data
# --> (u'0',)
You can also use LIMIT if you want to restrict the number of returned values with fetchall().
More importantly, don't format your queries like that. Get used to using the ? placeholder as a habit so that you are not vulnerable to SQL injection.
idvalue = c.execute("""SELECT ID FROM userdetails WHERE username = ?""", (username,)).fetchone()