所以我有以下命名元组,包含多个项目:
[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 的表中,这是我目前所拥有的:
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 模块连接到数据库。
感谢您的帮助。
最佳答案
假设项目真的是 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))
关于Python:在for循环中将命名元组添加到MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37323007/