【问题标题】:Using a Python variable in MySQL query在 MySQL 查询中使用 Python 变量
【发布时间】:2013-05-15 00:09:48
【问题描述】:

我正在尝试编写一个函数,该函数采用下面编写的函数placeholder() 中编写的变量,然后在 MySQL 查询中使用该变量。我在下面写了一个例子:

import MySQLdb
connection = MySQLdb.connect(host = "localhost", user = "root", 
                   passwd = "", db = "cars")
cursor = connection.cursor()

def placeholder(placeholder_variable):
    sql = "TRUNCATE TABLE %s"
    cursor.execute(sql, placeholder_variable)

placeholder('car_brands')

当我尝试运行此程序时,出现以下错误:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''car_brands'' at line 1")

这是针对大学作业的,必须使用placeholder('variable') 格式来接收变量。我已经花了几个小时在互联网上搜索试图找到解决方案,请帮助:/

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:
    sql = "TRUNCATE TABLE " + placeholder_variable + ";"
    cursor.execute(sql)
    

    【讨论】:

    【解决方案2】:

    SQL 参数不能用于 MySQL 的元数据。您将需要清理该值并正常替换它。

    【讨论】:

    • 感谢您的快速回复。我只是编程新手,不知道我会怎么做。你能帮帮我吗?
    • 使用正则表达式确保没有不应该出现的字符,然后正常替换。
    • 我刚刚对什么是正则表达式进行了一些研究,但我仍然不明白如何使用它来满足我的需要。有没有机会请给我一些示例代码?我真的很感激。作为一个新手,这东西有点过头了,但这个任务要在 24 小时内完成:S
    • 只要没有用户输入在这个地方使用,这个地方的卫生是可选的。为了保持更灵活,最好在变量周围加上反引号,例如sql = "TRUNCATE TABLE `" + placeholder_variable + "`"
    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 2020-06-16
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2018-05-14
    相关资源
    最近更新 更多