简体   繁体   English

使用字典插入MySQL

[英]Insert into mysql using dictionary

I want to do the following SQL statement: 我要执行以下SQL语句:

INSERT INTO myTable (name, year) VALUES ("David", 2016)

Is there a simple way to do the above INSERT using a dictionary: 有没有一种简单的方法可以使用字典执行上述INSERT

d = {
  "name": "David",
  "year": 2016
}

Perhaps something like: 也许像这样:

cursor.execute('INSERT INTO myTable (%s) VALUES (%s)', (d.keys(), d.values())

Or even: 甚至:

cursor.execute('INSERT INTO myTable %s', (d.items(),))

Assuming mysql-connector (but true of most SQL/Python libraries), the cursor expects a tuple with the values (for proper parameterization). 假设使用mysql-connector (但对于大多数SQL / Python库而言是正确的),则游标需要一个包含值的元组(用于正确的参数化)。 A dict is inherently not ordered, so you need to use an ordered dict to use the second example in your question and ensure the keys are in the same order as the table columns/fields. dict本质上是无序的,因此您需要使用有序的dict来在问题中使用第二个示例,并确保键与表列/字段的顺序相同。 So for example: 因此,例如:

from collections import OrderedDict

d = OrderedDict([("name", "David"), ("year", 2016)])

values_tuple = tuple([v for v in d.values()])
q = r'INSERT INTO myTable (%s'
for i in range(len(values_tuple)-1):  # I added first one above so -1
    q += r', %s'
q += ')'

cursor.execute(q, values_tuple)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM