【问题标题】:python insert into sql errorpython插入sql错误
【发布时间】:2017-11-17 09:01:59
【问题描述】:

当我尝试通过 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

【问题讨论】:

  • mysql.connector.errors.ProgrammingError: 1064: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 4 行的 ':title, :amount,'':description)' 附近使用正确的语法
  • 您应该在问题中说明这一点,并命名您用于连接的库。但是是什么让您认为它接受这种格式的命名参数?
  • 请不要尝试将查询的错误部分加粗,并按原样显示您的查询。

标签: python mysql sql python-2.7 insert-into


【解决方案1】:

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

【讨论】:

  • 如果我们使用sql = '''insert into ingredients (title, amount, description) values ({title}, {amount}, {description})''' sql = sql.format({"title":ingredient, "amount":num, "description":description}) cursor.execute(sql) 会出现什么问题,因为您对我想知道的答案投了反对票。
  • 这会使您暴露于 SQL 注入。 db API 支持参数是有原因的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多