V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
explist
V2EX  ›  Python

sqlite3 中 row_factory 疑问?

  •  
  •   explist · 2017-05-13 11:51:40 +08:00 · 1651 次点击
    这是一个创建于 2559 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面的代码中设置了:

    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 条回复    2017-05-14 02:26:12 +08:00
    TJT
        1
    TJT  
       2017-05-14 02:26:12 +08:00   ❤️ 1
    https://google.github.io/styleguide/pyguide.html?showone=Naming#Naming 先看这个

    因为你创建 cursor 是在设置 row_factory 之前,当然不起作用。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1027 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:06 · PVG 04:06 · LAX 13:06 · JFK 16:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.