在MySQL查询中使用Python变量

2024-05-19 14:00:15 发布

您现在位置: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')格式来接收变量。我花了几个小时在网上搜索,试图找到解决这个问题的方法,请帮助:/


Tags: theto函数sqlyourmysqlconnectioncar