Using a Python dict for a SQL INSERT statement

前端 未结 10 1350
小蘑菇
小蘑菇 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:05

    Always good answers here, but in Python 3, you should write the following:

    placeholder = ", ".join(["%s"] * len(dict))
    stmt = "insert into `{table}` ({columns}) values ({values});".format(table=table_name, columns=",".join(dict.keys()), values=placeholder)
    cur.execute(stmt, list(dict.values()))
    

    Don't forget to convert dict.values() to a list because in Python 3, dict.values() returns a view, not a list.

    Also, do NOT pour the dict.values() in stmt because it tears a quote out of a string by joining it, which caused MySQL error in inserting it. So you should always put it in cur.execute() dynamically.

提交回复
热议问题