2017-04-14 797 views
0

這個函數應該檢查用戶在提示後輸入的成分。當我在sqlite中嘗試這個查詢語句時(當然沒有用戶輸入)它可以工作。在Python中它說有一個錯誤!sqlite3「OperationalError:near」)「:syntax error」python

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

你能後整個錯誤消息?那是蟒蛇抱怨或SQL? – tdelaney

回答

1

您還沒有包含在您的查詢SQL參數佔位符。你必須放置一個?查詢您要插值每個值:

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

你可能想看看製作聯接,我懷疑使用嵌套的選擇是要執行那麼好。我懷疑,下面會更好地工作:

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

如果你想usrIngredient作爲一個字符串搜索來處理,你必須通配符添加到它的LIKE正常工作。與%字符環繞值:

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

這將替換字符串eggs%eggs%發現包含文本eggs所有匹配的成分說明。

0

也許是這樣的:

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,)) 
相關問題