sqlite3 中 row_factory 疑问?

2017-05-13 11:51:40 +08:00
 explist

下面的代码中设置了:

self.con.row_factory = dict_factory

但为什么最后未起作用呢?


import sqlite3 as sql

import os

def dict_factory(cur,row):

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

class LiMin:

def __init__(self,ProName):
    self.create_Project(ProName)
    self.con.row_factory = dict_factory

def create_Project(self,ProName):  # 创建或打开项目文件
    self.con = sql.connect(ProName)
    self.cur  = self.con.cursor()
    self._addTableStocks()  # 添加缺省 stocks 表
    self.con.commit()  
    
def _addTableStocks(self): # 添加 stocks 表 未提交事务
    self.cur.execute('create table if not exists stocks (name text ,number real)')  
    
def insertOne(self,data):   # 插入一条记录
    self.cur.execute('insert into stocks values (?,?)',data)

if name == 'main':

dirs = os.path.dirname(__file__)

pro = LiMin(os.path.join(dirs,'test.db'))
pro.con.row_factory = dict_factory

with pro.con: 
    pro.insertOne(('abc',33))
    pro.cur.execute('select * from stocks')
    
    print(type(pro.cur.fetchone())) # 为什么不是字典?        
    
    pro.cur.close()
1659 次点击
所在节点    Python
1 条回复
TJT
2017-05-14 02:26:12 +08:00
https://google.github.io/styleguide/pyguide.html?showone=Naming#Naming 先看这个

因为你创建 cursor 是在设置 row_factory 之前,当然不起作用。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/361053

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX