Python:在 for 循环中将命名元组添加到 MySQL

Python: adding named tuples to MySQL in a for loop

所以我有以下命名元组,包含多个项目:

[item(company='MARINE AND GENERAL MUTUAL LIFE ASSURANCE SOCIETY', google_name='no results', place_id='no results', formatted_address='no results'),
 item(company='KENTSTONE PROPERTIES LIMITED', google_name='no results', place_id='no results', formatted_address='no results'),
 item(company='ASHFORD CATTLE MARKET COMPANY LIMITED(THE)', google_name=u'The Ashford Cattle Market Co Ltd', place_id=u'ChIJRSxF4gbb3kcRCjmXJcSWOrI', formatted_address=u'The New Ashford Market Monument Way, Orbital Park, Ashford TN24 0HB, United Kingdom'),
 item(company='ORIENTAL GAS COMPANY, LIMITED(THE)', google_name=u'Orient Express Hotels', place_id=u'ChIJffRJYVVYwokReF_qwmzMgh0', formatted_address=u'1155 Ave of the Americas, New York, NY 10036, United States'),
 item(company='BRITISH INDIA STEAM NAVIGATION COMPANY LIMITED', google_name=u'British-India Steam-Navigation Co Ltd', place_id=u'ChIJe6yzIVN2AjoRZdGKagFvkvs', formatted_address=u'54/7, Bisha    Lakshmitala Road, Parnashree, Kolkata, West Bengal 700060, India')]

我想将这些项目添加到 MySQL 数据库中,添加到名为 place_id 的 table 中,这是我目前得到的:

cursor.execute("INSERT INTO place_id (company, google_name, place_id, formatted_address) VALUES (%(company)s, %(google_name)s, %(place_id), %(formatted_address)s" ....

而且我不知道从那里去哪里。

我想通过 for 循环(或 executemany,但我不太熟悉)添加项目。我已经通过 MySQLdb 模块连接到数据库。

感谢您的帮助。

在查询中使用 'named' 样式参数标记(例如 '%(company)s')需要您将 映射 与必要的键传递给 cursor.execute().由于您将元组传递给它,因此需要相应地更改标记(例如,使用 'format' 样式):

for i in items:
    cursor.execute("INSERT INTO place_id (company, google_name, place_id, "
                   "formatted_address) VALUES (%s, %s, %s, %s)", i)

或使用cursor.executemany():

cursor.executemany("INSERT INTO place_id (company, google_name, place_id, "
                   "formatted_address) VALUES (%s, %s, %s, %s)", items)

假设 item 确实是一个 namedtuple 并从参数的顺序推导出它被声明为

item = namedtuple('item', 'company google_name place_id formatted_address')

没有必要在您的查询中使用命名占位符,除非您真的想要。只需使用适用于元组的正常序列格式样式:

# assuming items is a reference to the list of item instances you gave
# in the example
cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%s, %s, %s, %s)", items)

要使用命名占位符版本,您可以使用 namedtuple._asdict 将项目列表转换为 OrderedDict 序列(映射序列),但实际上没有必要这样做:

cursor.executemany("INSERT INTO place_id "
                   "(company, google_name, place_id, formatted_address) "
                   "VALUES (%(company)s, %(google_name)s, %(place_id)s, %(formatted_address)s",
                   (i._asdict() for i in items))