Using a Python dict for a SQL INSERT statement

前端 未结 10 1349
小蘑菇
小蘑菇 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 22:55

    I used this thread for my usage and tried to keep it much simpler

    ins_qry = "INSERT INTO {tablename} ({columns}) VALUES {values};" .format(
                tablename=my_tablename,
                columns=', '.join(myDict.keys()),
                values=tuple(myDict.values())
            )
    cursor.execute(ins_qry)
    

    Make sure to commit the data inserted, either using db_connection.commit() and use cursor.lastrowid, if you need the primary key of the inserted row

提交回复
热议问题