SQL SELECT return的建议格式

2024-07-01 08:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

什么是定义所有这些变量的“更干净”的方法


Tags: idurlnumbertitlesdproviderseasonseries
1条回答
网友
1楼 · 发布于 2024-07-01 08:20:31

“最干净”的解决方案可能是使用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))

对于性能权衡,控制一次读取和类型转换的行数的完全缓冲/rowset-buffered/row-buffered选项也控制在dict或namedtuple中包装的行数。尽可能多地缓冲可能会快一点,但当然会消耗内存;当你真的需要对事情进行微调时,最好的解决办法可能是将一个结果分解成多个大小正好合适的结果集,并对每个结果集进行完全缓冲,但通常这是不值得做的

相关问题 更多 >

    热门问题