Using a Python variable in MySQL query

2019-01-28 23:25发布

I am trying to write a function that takes the variable written in the function placeholder() written below and then uses that in MySQL queries. I have written up an example below:

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')

When I try to run this program I get the following error:

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")

This is for a university assignment and MUST use the placeholder('variable') format to receive the variable. I have spent literally hours searching the internet trying to find a solution to this please help :/

2条回答
forever°为你锁心
2楼-- · 2019-01-28 23:48

SQL parameters cannot be used for metadata with MySQL. You will need to sanitize the value and substitute it normally.

查看更多
\"骚年 ilove
3楼-- · 2019-01-29 00:00
sql = "TRUNCATE TABLE " + placeholder_variable + ";"
cursor.execute(sql)
查看更多
登录 后发表回答