Using a Python dict for a SQL INSERT statement

前端 未结 10 1116
小蘑菇
小蘑菇 2020-11-28 22:43

I am trying to use a dict to do a SQL INSERT. The logic would basically be:

INSERT INTO table (dict.keys()) VALUES dict.values()


        
相关标签:
10条回答
  • 2020-11-28 23:07

    What about:

    keys = str(dict.keys())
    keys.replace('[', '(')
    keys.replace(']', ')')
    keys.replace("'",'')
    
    vals = str(dict.values())
    vals.replace('[', '(')
    vals.replace(']', ')')
    
    cur.execute('INSERT INTO table %s VALUES %s' % (keys, vals))
    

    For python 3:

    keys = str(dict.keys())[9:].replace('[', '').replace(']', '')
    vals = str(dict.values())[11:].replace('[', '').replace(']', '')
    

    ...

    0 讨论(0)
  • 2020-11-28 23:09

    This code worked for me (Python 3):

    fields = (str(list(dictionary.keys()))[1:-1])
    values = (str(list(dictionary.values()))[1:-1])
    sql = 'INSERT INTO Table (' + fields + ') VALUES (' + values + ')'
    cursor.execute(sql)
    

    It does rely on the dictionary outputting its keys and values in the same order. I'm unclear if this is always true :)

    0 讨论(0)
  • 2020-11-28 23:11
    table='mytable'    
    columns_string= '('+','.join(myDict.keys())+')'    
    values_string = '('+','.join(map(str,myDict.values()))+')'    
    sql = """INSERT INTO %s %s
         VALUES %s"""%(table, columns_string,values_string)
    
    0 讨论(0)
  • 2020-11-28 23:18

    You want to add parameter placeholders to the query. This might get you what you need:

    qmarks = ', '.join('?' * len(myDict))
    qry = "Insert Into Table (%s) Values (%s)" % (qmarks, qmarks)
    cursor.execute(qry, myDict.keys() + myDict.values())
    
    0 讨论(0)
提交回复
热议问题