代码之家  ›  专栏  ›  技术社区  ›  Ben Edwards

python插入sql错误

  •  0
  • Ben Edwards  · 技术社区  · 8 年前

    当我试图通过SQL将python代码中收集的一些值插入数据库时,我在下面的python代码中遇到了一个SQL错误。我在用粗体突出显示的代码上发现了一个SQL错误。感谢您的帮助!

    def add_ingredients(cursor) :
        while True:
          ingredient = raw_input("Name of ingredient (q to quit):")
          if ingredient.lower() !='q':
              num = raw_input("Number in storage: ")
              description = raw_input("description: ")
              sql = '''insert into ingredients 
                 (title, amount, description)
                values
                 **(:title, :amount, :description)'''**
              cursor.execute(sql,
               {"title":ingredient, "amount":num, "description":description})
              print "Added!"
          else:
              print "Okay, quitting."
              break
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Daniel Roseman    8 年前

    MySQL连接器不需要这样的命名参数。像 the documentation 显示,您应该使用 %(var_name)s 字典插值格式:

     sql = '''insert into ingredients (title, amount, description)
              values (%(title)s, %(amount)s, %(description)s)'''
      cursor.execute(sql, {"title": ingredient, "amount": num, "description": description})