SQL SELECT返回的建议格式

时间:2015-05-22 20:46:28

标签: python mysql

我在python代码中执行以下模式:

self.cursor1.execute(
     '''SELECT title, availed_title, episode_number,
               platform_id_series, platform_id_season, 
               platform_id_episode, season_number, url,
               provider_id, country, currency_code, est_hd_offer,                   
               est_sd_offer, vod_hd_offer, vod_sd_offer
     FROM main_googlecatalogtmp WHERE asset_type="episode"'''
)

item = cursor.fetchone()
title, availed_title, platform_id_series,
platform_id_season, platform_id_episode,
season_number, url, provider_id, country,
currency_code, est_hd_offer, est_sd_offer,
vod_hd_offer, vod_sd_offer = item

什么是'清洁剂'如何定义所有这些变量?

1 个答案:

答案 0 :(得分:2)

"最干净"解决方案可能是使用类似SQLAlchemy Core的东西,甚至是完整的ORM来封装。然后,您将编写仅查询匹配对象的代码,并且对象具有title属性,episode_number属性等。但这可能比您想要的更重,或者你的某些逻辑可能不太适合OODB模型,或者可能在这一点上改变的代码太多了。

但是你可以通过使用namedtuple样式的光标或行工厂来朝这个方向迈出一步。

假设您使用MySQL自己的Connector / Python作为接口,您可以显式指定游标类型(请参阅the list of all cursor subclasses),或指定标志并让它选择游标类型匹配那些标志。例如:

self.cursor1 = db.cursor(named_tuple=True)
# ...
self.cursor1.execute(
     '''SELECT title, availed_title, episode_number,
               platform_id_series, platform_id_season, 
               platform_id_episode, season_number, url,
               provider_id, country, currency_code, est_hd_offer,                   
               est_sd_offer, vod_hd_offer, vod_sd_offer
     FROM main_googlecatalogtmp WHERE asset_type="episode"'''
)
item = cursor.fetchone()
print('My title is {}'.format(item.title))

根据您的使用情况,dict可能比namedtuple更合适。例如:

self.cursor1 = db.cursor(dictionary=True)
# ...
self.cursor1.execute(
     '''SELECT title, availed_title, episode_number,
               platform_id_series, platform_id_season, 
               platform_id_episode, season_number, url,
               provider_id, country, currency_code, est_hd_offer,                   
               est_sd_offer, vod_hd_offer, vod_sd_offer
     FROM main_googlecatalogtmp WHERE asset_type="episode"'''
)
item = cursor.fetchone()
print('My title is {title} and my url is {url}'.format(**item))

对于性能权衡,相同的全缓冲/行集缓冲/行缓冲选项控制一次读取和类型转换的行数也控制dict或namedtuple中包含的行数。缓冲尽可能快一点,但当然它会花费内存;当你真的需要对事物进行微调时,最好的答案可能是将结果分解为多个完全正确大小的结果集,并完全缓冲每个结果集,但通常情况下这并不值得。