If Else condition on python - 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:

Related

Python check sqlite data exits?

I wrote few lines of code to check if data exist in database as below:
def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220722.2008";')
for row in result:
if row == (1,):
print("yes its here")
When the data exists it successfully printed "yes its here". However if I wrote lines as this:
def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute(f'select 1 from Summary1 where "Date Time" = "20220723.2008";')
for row in result:
if row == (1,):
print("yes its here")
else:
print("No its not here")
It fails to print "No its not here". Instead the program just run with nothing happens. I'm using Pycharm by the way.
Anyone knows what's going on? how can I get the false conditioned result pls?
Alternatively, any better code better way to achieve the same result would be appreciated.
Many thanks.
What is happening here is that in the event that no matching data be found, the result set is empty, and therefore the list which gets returned will be completely empty and also falsy. Try using this version:
def check_if_data_exists(self):
with self.connection as mycur:
result = mycur.execute("SELECT 1 FROM Summary1 WHERE \"Date Time\" = '20220723.2008'")
if result:
print("yes its here")
else:
print("No its not here")
Perhaps a more safe way to do this would be to use an exists query, and then just check the (single) boolean value returned:
def check_if_data_exists(self):
with self.connection as mycur:
mycur.execute("SELECT EXISTS (SELECT 1 FROM Summary1 WHERE \"Date Time\" = '20220723.2008')")
row = mycur.fetchone()
if row[0]:
print("yes its here")
else:
print("No its not here")
In the second version above, you would always get back a result set with a single record and boolean value.

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)

How to compare my string to the return in python

I have this code
log_in = f'SELECT user_name,fname FROM users;'
cursor = connection.cursor()
cursor.execute(log_in)
result = cursor.fetchall()
cursor.close()
print(type(result))
print(result)
print('bfuqua' in result)
if 'bfuqua' in result:
unique = False
print('That user name already exists. Please try again.')
When I print the type I get <class 'list'> as the return type, [('bfuqua',)] as the data from the result variable. My problem is that it should be entering into the if statement but the return from the third print statement says False. It comes back as True when I put result[0], but I need to be able to scan the whole list for the string. I don't know what is going on.
If there are any other ways I can check to see if the string is in the return from the query, I am more than open to hear it!
Well if you would like to use your code you can iterate over result to achieve what you want:
for i in result:
if 'bfuqua' in i:
unique = False
print('That user name already exists. Please try again.')
But if you want to do it in a way suggested by #iuvbio I'd do it like:
def check_if_user_exists(username):
#by using "with" you dont need to worry about closing the connection
with connection.cursor() as cursor:
log_in = "SELECT user_name, fname FROM users WHERE user_name = %s"
cursor.execute(log_in, (username,))
result = cursor.fetchall()
# If there is no user, the result will be a tuple with 0 length
if len(result) == 0:
print("No user named {}".format(username))
# So here you can create user
else:
print("User {} already exists".format(username))
# Here you can create a notification for a client that the username already exists
check_if_user_exists("bfuqua")
I'm also a beginner so dont treat it like the one and only good solution but it works for me. Hope I was able to help :)

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...

getting multiple values out of an SQL statement

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,))

Categories

Resources