当我不传递任何参数时,如何从"dict_factory"自动调用"dict_factory(cursor, row)"?



我对python开发非常陌生,在理解一个示例中使用的一种方法时遇到麻烦,方法是:

def dict_factory(cursor, row):
d={}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d

它被调用自:

conn = sqlite3.connect("books.db")
conn.row_factory = dict_factory
cur = conn.cursor()

现在的2个问题是:

  1. 如何在没有参数的情况下从dict_factory调用dict_factory(光标,列(?

  2. dict_factory(( 实际工作原理如何?枚举是否将数据库分解为 (c0,r0(、(c0,r1( 等格式?

按dict_factory转换后的数据库为:

[
{
"author": "Ann Leckie ", 
"first_sentence": "The body lay naked and facedown, a deathly gray, spatters of blood staining the snow around it.", 
"id": null, 
"published": 2014, 
"title": "Ancillary Justice"
}, 
{
"author": "John Scalzi", 
"first_sentence": "From the top of the large boulder he sat on, Ensign Tom Davis looked across the expanse of the cave, toward Captain Lucius Abernathy, Science Officer Qu2019eeng and Chief Engineer Paul West perched on a second, larger boulder, and thought, Well, this sucks.", 
"id": null, 
"published": 2013, 
"title": "Redshirts"
}
]
  1. 在您显示的代码中,未调用dict_factoryconn.row_factory = dict_factory只是将该函数分配给属性row_factory。这意味着您只是告诉数据库连接以哪种方式处理行(作为字典(。
  2. enumerate通过元素的索引来增强"正常"迭代(它返回元组(index, element)(。如果您执行了for col in cursor.description:col仅保存每列的名称。这样做for idx, col in enumerate(cursor.description):反而提供了元组,其中第一个元素是迭代索引(从 0 开始(,即(0, col0), (1, col1), ....现在,该函数dict_factoryrow转换为dict。它通过迭代各种列并将col_name: row_value_for_that_column的键值对添加到字典来实现。

最新更新