擅长:python、mysql、java
<p>假设字典列表至少包含一个条目,并且每个条目都有相同的键,则可以执行以下操作:</p>
<pre><code>def func(table_name, args):
names = list(args[0].keys())
column_names = ",".join(names)
bv_names = ",".join(":" + n for n in names)
sql = f"insert into {table_name} ({column_names}) values ({bv_names})"
cursor.executemany(sql, args)
</code></pre>
<p>第一行假设args中至少有一个条目,它是一个字典,并且所有后续条目也是具有相同键的字典。如果这些假设中的任何一个不正确,功能将失败</p>
<p>接下来的几行构建了要使用绑定变量执行的SQL</p>