getting multiple values out of an SQL statement - python

What I am trying to is work out whether there are teachers with duplicate initials. I tried to do this by returning one value from the database file with the searched for initials. Then returning all the values with the searched initials. Then I wanted to check the first value against the second, and if they were not equal there must be a duplicate.
Is there a way of doing this and is there an easier way of doing this?
Thanks
def FindTeacherID(TeacherInitials):
with sqlite3.connect("TeacherInfo.db") as db:
cursor = db.cursor()
cursor.execute("select TeacherID from TeacherInfo where TeacherInitials = ?",(TeacherInitials,))
Value = cursor.fetchone()
cursor.execute("select TeacherID from TeacherInfo where TeacherInitials =?",(TeacherInitials,))
ValueTest = cursor.fetchall()
if Value == None:
print("There are no teachers in the list")
else:
Value = str('.'.join(str(x) for x in Value))
ValueTest = str('.'.join(str(x) for x in Value))
if ValueTest == Value:
DeleteTeacher(Value)
else:
print("There is a duplicate in teacher initials")

Just use only 1 query where you get the count:
cursor.execute("select Count(TeacherID) from TeacherInfo where TeacherInitials = ?",(TeacherInitials,))

Related

Return message when entry not in db

I'm trying to create a script which will check if entry is in connected database, if found it will return entry and if not it will ask if user wants to add it. Script is connecting db without problems, and retrun correct information when entry is found. But when entry is not in db nothing is returned back. I tried two different ways
Tuple doesn't exist:
# get vrn
def vrn_exist():
vrn = input('Registration Number: ')
vrn = vrn.upper()
# check if vrn is in database
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
cursor.fetchone()
if not row:
print("NO")
continue
else:
print("YES")
len of tuple:
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
data = cursor.fetchone()
# print(row)
# return True
# if entry is in database show details
if len(row) != 0:
car_details(row)
# if entry not in database insert new line
elif len(data) == 0:
print('Car not in db. Would you like to add it?')
Since you're using fetchone it will return None if no data is match in your query.
for row in cursor.execute("SELECT * FROM vw_vehicles WHERE regnum= ?", [vrn]):
data=cursor.fetchone()
#if entry is in database show details
if data != None:
car_details(row)
#if entry not in database insert new line
elif data == None:
print('Car not in db. Would you like to add it?')
Rather than using a loop to process one result, ask the database for the first row using fetchone(). If there's no record, it'll return None, so you can react accordingly:
data = cursor.execute("SELECT * FROM vw_vehicles WHERE regnum=?;", [vrn]).fetchone()
if data is None:
print("Car not in db. Would you like to add it?")
else:
car_details(data)

Trying to update my quantity of stock by updating the a value into my database that i got out earlier by using the ID

need to update my SQL database with new number but I cant seem to be able to do so. I'm using python with SQLite I'm not really any good at SQL so any help would be appreciated. I couldn't find a way to update it straight away so I thought a work around would be to get the number from the database then turn it back into a string to be enter back in. I'm sure I'm making this more difficult then it needs to be ive been stuck for a long time and really just dont know what to do now
def delete():
#create a database or connect ot one
conn = sqlite3.connect('Food_item.db')
#create cursor
c = conn.cursor()
# Delete a record
if (len(f_name_editor.get()) != None and len(l_name_editor.get()) == 0):
print ("hello")
c.execute("DELETE from FOOD WHERE oid= " + f_name_editor.get())
elif (len(f_name_editor.get()) != None and len(l_name_editor.get()) != None):
c.execute("SELECT QUANTITY FROM FOOD WHERE ADMIN_ID= "+ f_name_editor.get())
record_id = f_name_editor.get()
records = c.fetchone()[0]
sub_num= l_name_editor.get()
new_items= (records-int(sub_num))
Removed_items =str(new_items)
print(Removed_items)
c.execute("UPDATE QUANTITY FROM FOOD =" +Removed_items+" WHERE ADMIN_ID= "+f_name_editor.get())
The UPDATE SQL in your code is invalid, it should be:
c.execute('UPDATE FOOD SET QUANTITY = ? WHERE ADMIN_ID = ?',
(Removed_items, f_name_editor.get()))
conn.commit()
Better use placeholders to avoid SQL injection and you need to call conn.commit() to make the update effective.
Note that if l_name_editor.get() is the amount to be deducted from QUANTITY, you don't need to get the current QUANTITY. Just use one UPDATE SQL as below:
c.execute('UPDATE FOOD SET QUANTITY = QUANTITY - ? WHERE ADMIN_ID = ?',
(l_name_editor.get(), f_name_editor.get()))
conn.commit()

How to delete row in PostgreSQL using Python?

I want to delete the whole row when user enters the id. If it matches, I completely delete whole row from table.
#staticmethod
def close_account(value):
check()
rows = cur.fetchall()
for row in rows:
if rows is None:
print("Sorry It's an Empty.............. ")
return True
elif rows[0] == value:
del_row = "Delete From customer where id = value"
cur.execute(del_row)
return True
It shows error in del_row that:
value is unable to resolve column value
Even if I enter the id = 1 it also does not delete the row.
Considering your id attribute is a string, change this line:
del_row = "Delete From customer where id = value"
to:
del_row = "Delete From customer where id = %s" % value
The way you have it, the database is trying to delete DELETE FROM customer WHERE id="value", whereas your goal is to replace value with the function parameter (e.g. DELETE FROM customer WHERE id="123"
Disclaimer: This solution makes your code susceptible to SQL injection
There are a couple of problems here. Primarily you're not passing a value in for the id = X condition in your query, so you'll need to do that - preferably using a parameterized query, that looks like this:
del_row = "DELETE FROM customer WHERE id = %s"
cur.execute(del_row, (1))
Your second problem is the assumption that the row ID is 1, when this may not be the case. If your ID field is auto incrementing, then it may be far greater than that. If your original query is returning the ID as a column, you should be able to retrieve the row ID using something like:
row[0]
Which, when passed into the first code block, means you end up with something like this:
#staticmethod
def close_account(value):
check()
rows = cur.fetchall()
for row in rows:
if rows is None:
print("Sorry It's an Empty.............. ")
return True
elif rows[0] == value:
del_row = "DELETE FROM customer WHERE id = %s"
cur.execute(del_row, row[0])
return True
"Delete From customer where id = %s" % value
will possibly get you what you want. On the other hand, it's a bad idea to programatically walk through all rows of the database to find a single one to delete, but I guess there are even bigger fish to fry first...

If Else condition on python

I am trying to place a condition after the for loop. It will print the word available if the retrieved rows is not equal to zero, however if I would be entering a value which is not stored in my database, it will return a message. My problem here is that, if I'd be inputting value that isn't stored on my database, it would not go to the else statement. I'm new to this. What would be my mistake in this function?
def search(title):
query = "SELECT * FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
rows = cursor.fetchall()
for row in rows:
if row != 0:
print('Available')
else:
print('No available copies of the said book in the library')
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
def main():
title = input("Enter book title: ")
search(title)
if __name__ == '__main__':
main()
Quite apart from the 0/NULL confusion, your logic is wrong. If there are no matching rows, you won't get a 0 as the value of a row; in fact you won't get any rows at all, and you will never even get into the for loop.
A much better way to do this would be simply run a COUNT query, get the single result with fetchone(), and check that directly.
query = "SELECT COUNT(*) FROM books WHERE title = %s"
entry = (title,)
try:
conn = mysql.connector.connect(user='root', password='', database='python_mysql') # connect to the database server
cursor = conn.cursor()
cursor.execute(query, entry)
result = cursor.fetchone()
if result != 0:
print('Available')
else:
print('No available copies of the said book in the library')
First of all NULL in python is called None.
Next:
according to documentation:
"The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.
"
enpty list is not None
>>> row = []
>>> row is None
False
So you need to redesign your if statment in the way like this:
for i in rows:
if i:
blah-blah
else:
blah-blah-blah
In python you should check for None not NULL. In your code you can just check for object, if it is not None then control should go inside if otherwise else will be executed
for row in rows:
if row:
print('Available')
else:
print('No available copies of the said book in the library')
UPDATE after auther edited the question:
Now in for loop you should check for column value not the whole row. If your column name is suppose quantity then if statement should be like this
if row["quantity"] != 0:

TypeError: 'float' object has no attribute '__getitem__'

I use the following code to make a booking in a system yet it returns an error:
conn = sqlite3.connect('SADS.db')
cur = conn.cursor()
choice = raw_input("What day would you like to book seats on? F/S : ")
if choice == "F":
bookseats = [0,1]
print"What seats would you like to book?"
bookseats[0] = raw_input("Choice : ")
bookseats[1] = raw_input("What is their user ID? : ")
cur.execute("SELECT * FROM seats WHERE Booked='N'")
rows = cur.fetchone()
for row in rows:
if row == None:
break
elif row[1] == bookseats[0] and row[4] == "N" and row[3] == "F":
print "Seat Number:" , row[1] ,"Is now booked!"
cur.execute("UPDATE seats SET Booked =N AND CustID=?", (bookseats[0]))
Error:
TypeError: 'float' object has no attribute '__getitem__'
I am really confused what the error is and how I fix it?
You are looping over the result of rows = cur.fetchone(), which retrieves just one row. Remove that line and just loop directly over the cursor:
cur.execute("SELECT * FROM seats WHERE Booked='N'")
for row in cur:
You do not need to test for row == None either, nor do you need to test if the Booked column is equal to N. Simplify the loop to:
cur.execute("SELECT * FROM seats WHERE Booked='N' AND CustID=?", (bookseats[0],))
row = cur.fetchone()
if row is not None and row[3] == "F":
print "Seat Number:" , row[1] ,"Is now booked!"
cur.execute("UPDATE seats SET Booked =N AND CustID=?", (bookseats[0]))
You can just ask the database for rows that match your bookseats[0] column, and where the 3rd column is set to F. You didn't show us your schema so it is hard to recommend how you can update your query for that.
Your UPDATE query is incorrect, you probably meant:
cur.execute("UPDATE seats SET Booked='Y' WHERE CustID=?", (bookseats[0],))
instead.
Your SQL query and update look suspect though; without knowing the full schema it does look as if you are mixing your seat number and customer number in places.
fetchone doesn't return a list of rows, but one row only, so this is incorrect:
rows = cur.fetchone()
for row in rows:
Do, instead:
row = cur.fetchone()

Categories

Resources