Skip to content Skip to sidebar Skip to footer

How To Compare Input Value With Mysql Database Value In Python

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

Solution 1:

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.

Solution 2:

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 = Falsefor x in result:
    if inputvalue in x:
        temp = Trueif temp:
    print(inputvalue)
else:
    print("Data Does Not Exist")

Post a Comment for "How To Compare Input Value With Mysql Database Value In Python"