下面的代码中设置了:
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()
1
TJT 2017-05-14 02:26:12 +08:00 1
https://google.github.io/styleguide/pyguide.html?showone=Naming#Naming 先看这个
因为你创建 cursor 是在设置 row_factory 之前,当然不起作用。 |