Python check sqlite data exits? - python

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.

Related

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

read a file line by line and print only after its done

So I am working on doing a "simple" task since like 2h and still can't find the solution, so where is my question :
I want to search in a file, line by line, and if no result is found, at the end print something, else call a function.
def DeletItemCheckUp():
import re
find = True
itemNumber = input("\n what is the item you want to delet : ")
fileItem = open('Data_Item', 'r', encoding='Utf-8')
for line in fileItem:
sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
if (sr == None):
pass
print("This item don't exist.")
fileItem.close()
if (find == True):
return itemNumber
DeletItem()
so here is the problem I have got with different try :
1. Print "This item don't exist." for every line that didn't had my itemNumber.
2. When there was actually no match found, its would not call DeletItem().
objectif of the code :
Ask for a item to delet, check in a file if the unique item number exist, if so, call DeletItem() to delet it, else, tell the user that this unique item number don't exist.
Few overlooks in there to achieve what you ask. We are going to use a flag (true/false) to know when we found something, and based on that we will decide whether to call the function or print/return the number.
def DeletItemCheckUp():
import re
find = False # initialize to False
itemNumber = input("\n what is the item you want to delet : ")
fileItem = open('Data_Item', 'r', encoding='Utf-8')
for line in fileItem:
sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
if (sr == None):
continue # do nothing and continue
else:
# we found the number, set the flag and break
find = True
break # no need to continue searching
fileItem.close()
if (find):
DeletItem() # call the function
else:
print("This item don't exist.")
1) replace the pass with your print('This item doesn't exist'). "Pass" means "do nothing."
2) Your DeleteItem() is after the return. Nothing executes after the return because you have returned to the place the function was called from. You want
else:
DeleteItem()

How do i get python to remove the row i search for from csv file

I am able to edit and add new entries but everytime i try to delete the row i search for, it wipes the whole files data.
I need it to just remove that row of data without losing the rest of the rows.
import csv,os,sys
def helper(file):
o=csv.reader(open(file,"r"))
for row in o:
print row
def delete(filename):
found=False
f1=csv.reader(open(filename,'r'))
f2=csv.writer(open("temp.csv",'a'))
rid=raw_input("Enter name to find record:")
for row in f1:
if rid in row[0]:
found=True
f2.writerow()
print rid, "has been deleted from the database!"
else:
found=False
if found==False:
print "That name isn't in our database!"
z=raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
if z=="1":
delete(filename)
if z=="2":
import program
if z=="3":
exit
helping=raw_input("Do you require any help with using this feature?Type y for yes or just hit enter to continue:")
if helping=="y":
helper('deletehelp.txt')
delete("custdet.csv")
os.remove("custdet.csv")
os.rename("temp.csv","custdet.csv") #This is the file rename that I mentioned above.
restart=raw_input("Would you like to return to the main menu? Please type Y or just hit enter to exit:")
if restart=="y":
import program
else: exit
import csv,os,sys
def helper(file):
o = csv.reader(open(file,"r"))
for row in o:
print row
def delete(filename):
f1 = csv.reader(open(filename,'r'))
f2 = csv.writer(open("temp.csv",'a'))
rid = raw_input("Enter name to find record:")
found = False
for row in f1:
if rid not in row[0]:
f2.writerow(row)
else:
found = True
print rid, "has been deleted from the database!"
if found == False:
print "That name isn't in our database!"
z = raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
if z == "1":
delete(filename)
if z == "2":
import program
if z == "3":
exit
You never actually write to the new csv file.
Look at the main filter/copy loop:
# for every row in the input file
for row in f1:
# Is this the/a record to delete?
if rid in row[0]:
# yes!
found=True
# then we do not write anything to the output file (???)
f2.writerow()
print rid, "has been deleted from the database!"
# no else part, so no nothing gets done with
# the input row `row` ...
So you'll end up with an empty output file ...
Change the section containing the for loop to this:
for row in f1:
if rid in row[0]:
found=True
print rid, "has been deleted from the database!"
else:
f2.writerow(row)
The changes:
Actually write the row if rid is not in row[0]
Don't reset the found flag to False
The rest of the code also needs some work:
Recursion is not the best way to handle retries, use a loop instead.
import program to return to the login ????? That's not going to
work. Perhaps you should just return from the function.
There is coupling between delete() and the calling code which
relies on a file named temp.csv being created. It would be much
better if delete() performed the renaming of the temporary file itself.

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:

Saving/Loading lists in Python

I am new to python (and programming in general) and am making a database/register for a typical class. I wanted the user to be able to add and remove pupils from the database, I used lists primarily for this but have hit a stump.
Whenever I restart the program the list the user has modified returns back to the defualt list I specified in the code. I looked around the internet and tried to save the list onto a seperate txt file. However the txt file also goes back to the defualt every time I restart the program. I would like you to please give me a way to save the changes made to the list and keep them that way. Here is the code (it's not very good):
def menu():
print "*****************CLASS REGISTER*****************"
print "Press 1 See The List Of Pupils"
print "Press 2 To Add New Pupils"
print "Press 3 To Remove Pupils"
print "Press 0 To Quit \n"
filename = open('pupil.txt','r')
pupil = ["James Steele", "Blain Krontick", "Leeroy Jenkins", "Tanvir Choudrey"]
def see_list(x):
print x
def add_pupil(x):
print "You have chosen to add a new pupil.\n"
option = raw_input("Please type the childs name.")
x.append(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been added to the system."
return x
def delete_pupil(x):
print "You have chosen to remove a pupil.\n"
option = raw_input("Please type the childs name.")
if option in x:
x.remove(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been removed from the system."
else:
print "That person is not in the system."
return x
one = 1
while one != 0:
menu()
option = input()
if option == 1:
see_list(pupil)
elif option == 2:
add_pupil(pupil)
elif option == 3:
delete_pupil(pupil)
elif option == 0:
break
else:
print "That is not a valible choice."
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
if option == 0:
quit
Well, you just open the pupil.txt file but never read back its contents. You need something like this:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()
pupil = [name for name in contents.split('\n') if name]
Also, you will need to handle the case when the pupil.txt file does not exist; this can be done with a try..except block around the IO calls.
Finally, as one of the comments has mentioned above, have a look at the pickle module, which lets you store a Python object in a file in Python's internal format (which is not really readable, but saves you a lot of hassle).
Not related to your question directly, but this:
one = 1
while one != 0:
...
is silly. All you need is:
while True:
...
This is what a database is for. Use sqlite - a simple file-based database the libraries for which come bundled with python.

Categories

Resources