Using a Python variable in MySQL query

浪子不回头ぞ 提交于 2019-11-28 10:49:00

问题


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 :/


回答1:


sql = "TRUNCATE TABLE " + placeholder_variable + ";"
cursor.execute(sql)



回答2:


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



来源:https://stackoverflow.com/questions/16649447/using-a-python-variable-in-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!