简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM