'Check if a string list exists in database
I am trying to check if a certain string variables list exists in a database using python.
I'm implementing the logic in a method called get_df using the method product_exist which checks if the product exist in the database or not:
# listof_products = ["Apple","Carrot"] or listof_products = ["Apple"] listof_products = ["fakeproduct"] or listof_products = ["Apple","Carrot","fakeproduct] / it can take 1 to n products.
def product_exist(product):
with conn.cursor() as crsr:
crsr.execute("SELECT product_name from tbl_Products where product_name = ?;",product)
result = crsr.fetchone()
if result is None:
return False
else:
return True
def get_df(self, query, listof):
conn = self.get_engine() # pyodbc connexion
crsr = conn.cursor()
for product in listof: # For every product among the product list (1 to n) check if product exist in database and return df else throw an error message.
if product_exist(product):
data = crsr.execute(query, listof).fetchall()
rows = [list(x) for x in data]
columns = [column[0] for column in crsr.description]
df = pd.DataFrame(rows, columns=columns)
return df
else:
print("Product {} do not exist in database".format(product))
break
get_df should return the corresponding dataframe given the query. Else if one of the products invoked in the list of products does not exist in the database then it will print an error message and continue parsing the rest of the list and return the corresponding dataframe for those products (existing products).
With the code above of get_df, it return a dataframe corresponding for only the 1st product in the list and not all the product elements of the list that exist in the database.
What is the correct way to implement the logic in the get_df method using pyodbc ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
