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

So I have the following namedtuple, containing multiple items:

[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')]

I would like to add those items to MySQL database, to the table called place_id, this is what I've got so far:

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

And I don't know where to go from there.

I would like to add the items via for loop (or executemany, but I am not that familiar with it). I am already connected to the database via MySQLdb module.

Thank you for your help.

解决方案

Assuming item really is a namedtuple and deducing from the order of arguments that it's declared like

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

there's no need to use named placeholders in your query, unless you really want to. Just use the normal sequence formatting style that works with tuples:

# 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)

To use the named placeholder version you could convert the list of items to a sequence of OrderedDicts (a sequence of mappings) with namedtuple._asdict, but there's really no need for this:

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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值