1

I'm trying to execute the following code in python, but it results in syntax error near '(' error for executemany(..). When I remove te names from sql and just write %s it also results in the error that there are more placeholders thant the variables does anyone know how I can fix it?

upInfo ={"aa": "aaa","bb": "bbb","cc": "ccc"}
sql = 'UPDATE table SET a=  %(aa)s WHERE b= %(bb)s and c= %(cc)s'
con = pymssql.connect(...)
con.autocommit(True)
cur = con.cursor()
cur.executemany(sql, upInfo)

1 Answers1

0

Since this is executemany(), it should be a list of dictionaries:

upInfo = [{"aa": "aaa", "bb": "bbb", "cc": "ccc"}]

Or, use a regular execute():

cur.execute(sql, upInfo)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks for your answer, it works, but I'm passing an object to my python file at a time. since it is only one dictionary, I'd rather not to deal with it as a list. Do you know any other safe way rather than executemany which works the same way? –  Jan 28 '15 at 14:49
  • 1
    @user4103576 ok, but why not use a regular `execute()` here? Thanks. – alecxe Jan 28 '15 at 14:52
  • Since it is [not safe](http://dev.mysql.com/doc/refman/5.1/en/stored-programs-logging.html) I'd rather use placeholders –  Jan 28 '15 at 14:56
  • 2
    `execute(stmt, {"aa": "aaa", "bb": "bbb", "cc": "ccc"})` is as safe as `executemany(stmt,[{"aa": "aaa", "bb": "bbb", "cc": "ccc"}])`. Both use [prepared statements and will bind values](https://www.python.org/dev/peps/pep-0249/#id16). Or am I wrong ? – Sylvain Leroux Jan 28 '15 at 15:06
  • Sorry, my bad! I didn't know that `execute` has the option of placeholders like `executemany`. Thanks for the answer –  Jan 28 '15 at 15:15