Nicco Narbutas
Nicco Narbutas

Reputation: 11

sqlite3 “OperationalError: near ”)“: syntax error” python

This function is supposed to check for the ingredient the user entered following the prompt. When I try this query statement in sqlite (without the user input of course) it works. In python it says there is an error!

def checkIngredient():

   usrIngredient = input("\nEnter an ingredient that you would like to make a drink with: \n\n")

    query = c.execute("SELECT DRDESC FROM Drinks WHERE DRDRID IN "
    "(SELECT DTDRID FROM Detail WHERE INGID ="
    "(SELECT INGID FROM Ingredients WHERE INDESC LIKE))", (usrIngredient,))


    resultset = c.fetchall()

    for result in resultset:
        if resultset is not None:
            print(result)
        else:
            print("Sorry, there are no drinks with that ingredient")

Upvotes: 0

Views: 1379

Answers (2)

AffableAmbler
AffableAmbler

Reputation: 427

Maybe something like this:

query=c.execute("""SELECT Drinks.DRDESC
                   FROM Drinks JOIN Detail JOIN Ingredients
                   ON Drinks.DRDRID = Detail.DTDRID
                   AND Detail.INGID = Ingredients.INGID
                   where Ingredients.INDESC like ?""",(usrIngredient,) )

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121336

You haven't included a SQL parameter placeholder in your query. You'll have to place a ? in the query for each value you want to interpolate:

query = c.execute("""
    SELECT DRDESC FROM Drinks WHERE DRDRID IN
      (SELECT DTDRID FROM Detail WHERE INGID =
        (SELECT INGID FROM Ingredients WHERE INDESC LIKE ?))
    """, (usrIngredient,))

You may want to look into making joins, I doubt that using nested selects is going to perform all that well. I suspect that the following would work better:

query = c.execute("""
    SELECT dr.DRDESC
    FROM Drinks as dr 
    INNER JOIN Detail as dtd on dr.DRDRID == dtd.DTDRID
    INNER JOIN Ingredients as ing on dtd.INGID = ing.INGID
    WHERE ing.INDESC LIKE ?
    """, (usrIngredient,))

If you wanted usrIngredient to be treated as a substring search, you'll have to add wildcards to it for LIKE to work correctly. Surround the value with % characters:

usrIngredient = '%{}%'.format(usrIngredient)

This replaces the string eggs with %eggs% to find all matching ingredient descriptions that contain the text eggs.

Upvotes: 1

Related Questions