How to update mysql with python where fields and entries are from a dictionary?

后端 未结 2 640
太阳男子
太阳男子 2020-12-31 14:46

I am trying to create a re-usable mysql statement for updating from a dictionary where the keys are the database fields and the data to go into that field is the value assoc

相关标签:
2条回答
  • 2020-12-31 15:38

    You don't want to be putting literal values in using string interpolation - SQL injection attacks are not a Good Thing(tm). Instead, you use the placeholder syntax relevant for your database (I think MySQL's is '%s').

    Note: I'm using .format here, change to use % if you want, but escape any %'s

    d = {'col1': 'val1', 'col2': 'val2'}
    sql = 'UPDATE table SET {}'.format(', '.join('{}=%s'.format(k) for k in d))
    print sql
    # 'UPDATE table SET col2=%s, col1=%s'
    

    Assuming cur is a DB cursor the correct way to perform the query is:

    cur.execute(sql, d.values())
    

    This works because although the ordering of a dictionary is effectively arbitrary order, the order of keys/values of a dict will be consistent such that dict(zip(d.keys(), d.values())) == d.

    0 讨论(0)
  • 2020-12-31 15:44

    how about trying

    stmt = "UPDATE TABLE table_name SET "
    for k,v in di.items():
        stmt += "%s = %s, " %(k,v)
    
    stmt = stmt[-2:]
    
    0 讨论(0)
提交回复
热议问题