在MySQL查询中使用Python变量

发布于 2021-01-29 15:04:54

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

关注者
0
被浏览
79
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    sql = "TRUNCATE TABLE " + placeholder_variable + ";"
    cursor.execute(sql)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看