Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted
sql = "TRUNCATE TABLE " + placeholder_variable + ";"
cursor.execute(sql)
share|improve this answer
add comment

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

share|improve this answer
    
Thanks for the quick response. I am only new at programming and am not sure how I would do this. Could you please help me out? –  Veiocity May 20 '13 at 12:33
    
Use a regex to make sure there are no characters that shouldn't be there, and then substitute it in normally. –  Ignacio Vazquez-Abrams May 20 '13 at 12:35
    
I have just done some research on what a regex is but I still don't understand how to use one for what I need. Any chance you could please give me some example code? I would really appreciate it. This stuff is a bit over my head as a novice but this assignment is due in 24 hours :S –  Veiocity May 20 '13 at 12:52
    
As long as there is no user input which gets used in this place, the sanitation is optional at this place. In order to stay more flexible, it might be approriate to put backticks around the variable, such as sql = "TRUNCATE TABLE `" + placeholder_variable + "`". –  glglgl May 21 '13 at 11:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.