在MySQL查询中使用Python变量

时间:2013-05-20 12:22:12

标签: python mysql mysql-python

我正在尝试编写一个函数,该函数接受在下面写的函数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')格式来接收变量。我花了几个小时搜索互联网,试图找到解决方案,请帮助:/

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

sql = "TRUNCATE TABLE " + placeholder_variable + ";"
cursor.execute(sql)
相关问题