0

So I want to compare the input value with my database value. IF the input value is the same value as the database, I want to print(inputvalue). But if it's not the same, I want to print("Data Does Not Exist")

So I've tried this code :

cur = connection.cursor()
query = """ SELECT * FROM `foo` """

cur.execute(query)
result = cur.fetchall()
inputvalue = input("Input= ")

for x in result:
    if inputvalue not in x:
        print("Data Does Not Exist")
    else:
        print(inputvalue)

and this is the output:

inputvalue= 1728192
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist
1728192
Data Does Not Exist
Data Does Not Exist
Data Does Not Exist

I expect the output is

Inputvalue= 1728192
Data Does Not Exist

If the Data Does Not Exist, And this output:

Inputvalue= 1728192
1728192

If the Data Exist
Any answer would be appreciated!

2 Answers 2

2

Instead of loading all the rows from foo into python, I would suggest to query if that specific value is in your database. Databases are optimised for such a request. And if there is a lot of data in your database, your approach would need a lot of time to load everything into memory (which can easily result in a memoryError).

So I guess you store your values in a column called 'bar':

inputvalue = input("Input= ")
cur = connection.cursor()
query = """ SELECT * FROM `foo` WHERE bar = inputvalue """

cur.execute(query)
row_count = cur.rowcount
if row_count > 0:
    print(inputvalue)
else:
    print("Data Does Not Exist")

And for you to understand why your approach is not working as expected: With for x in result: you loop through every row in your table, and for each row, you check if inputvalue is in there.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thank you for your answer, your code is working!. And thank you for pointing out my mistake
1

you can make boolean object and after executing compare your answer :

cur = connection.cursor()
query = """ SELECT * FROM `foo` """

cur.execute(query)
result = cur.fetchall()
inputvalue = input("Input= ")

temp = False
for x in result:
    if inputvalue in x:
        temp = True
if temp:
    print(inputvalue)
else:
    print("Data Does Not Exist")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.