user2876777
user2876777

Reputation: 13

Passing variables (table name,data) into python mysqld query

I am trying to pass the name of the table and information to be inserted into the table as parameters. The query I have come up with is below:

sql = """INSERT INTO `%s` (title,link,description) VALUES(%%s,%%s,%%s)""" % (feed,title_xml,link_xml,description_xml)
cursor.execute(sql)

However, I am getting the following error:

Traceback (most recent call last):
  File "slicer_1.py", line 41, in <module>
    sql = """INSERT INTO `%s` (title,link,description) VALUES(%%s,%%s,%%s)""" %(feed,title_xml,link_xml,description_xml)
TypeError: not all arguments converted during string formatting

What could be wrong here?

Upvotes: 1

Views: 1116

Answers (1)

BrenBarn
BrenBarn

Reputation: 251378

You have double %% on the last three %s. This means that only the first %s will be substituted in the string substitution, which means you can only pass one value to be substituted. Perhaps you meant to pass the other three to the execute call to be handled by the SQL library's safe substitution? Either that or you need to make all four have just one % so they all get substituted in the first step. (I'm not sure if things like MySQLdb let you parameterize VALUES data.)

Edit: If you take the second suggestion, you probably want to do it like this:

"""INSERT INTO `%s` (title,link,description) VALUES("%s","%s","%s")""" % (feed,title_xml,link_xml,description_xml)

Upvotes: 1

Related Questions