【问题标题】:Using Python variables in MySQL insert statement在 MySQL 插入语句中使用 Python 变量
【发布时间】:2016-09-21 04:16:12
【问题描述】:

我已经尝试了一段时间了,在网上看了一下,无法弄清楚。

变量是numbersanimals

sql = ("INSERT INTO favourite (number, info) VALUES (numbers, animals  )")
cursor.execute(*sql)
conn.comit()

【问题讨论】:

标签: python mysql database python-2.7


【解决方案1】:

这是对我有用的替代解决方案

cursor = conn.cursor()
query ="INSERT INTO favourite (number, info) VALUES ('"+ variable1  +"','"+  variable2+"')"
cursor.execute(query)
conn.commit()

【讨论】:

    【解决方案2】:

    我认为以下应该可行。让我知道你的效果如何。

    sql=("INSERT INTO favorite (number, info) VALUES ({},{})".format(numbers,animals))

    【讨论】:

    • 感谢您的反对。如果您认为可以,请改进答案!
    【解决方案3】:

    用途:

    sql=("INSERT INTO favourite (number, info) VALUES ({},{})".format(numbers,animals))
    

    根据将来的参考资料使用格式总是好的。 检查https://docs.python.org/release/3.1.5/library/stdtypes.html#old-string-formatting-operations

    【讨论】:

    • 不要在 SQL 语句中手动插入参数。您需要正确引用这些值,并且选择的 SQL 连接器库始终提供此功能。
    【解决方案4】:
    sql = ("INSERT INTO favourite (number, info) VALUES (%s, %s)", (numbers, animals))
    

    为了安全,请始终使用转义,请参阅http://dev.mysql.com/doc/refman/5.7/en/string-literals.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多