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
pc10201
V2EX  ›  Python

python3 如何像 python2 一样,连接数据库时返回字典数据?

  •  
  •   pc10201 · 2016-03-18 17:52:40 +08:00 · 2522 次点击
    这是一个创建于 2982 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在 python 2 中连接 mysql 代码
    import MySQLdb
    import MySQLdb.cursors

    conn = MySQLdb.connect(
    host="127.0.0.1",
    user="root",
    passwd="root",
    db="database",
    charset='utf8',
    use_unicode=True,
    cursorclass=MySQLdb.cursors.DictCursor
    )

    conn.ping(True)
    conn.autocommit(True)
    cur=conn.cursor()
    cur.execute("select xx from xxx")
    cur.fetchone()
    再执行查询 sql 就可以直接返回字典格式的数据

    但在 python 3 我好像没有找到一个库达到类似的效果,有的是要求自己加一个转换函数~
    7 条回复    2016-03-18 22:19:25 +08:00
    lxy
        1
    lxy  
       2016-03-18 18:24:31 +08:00   ❤️ 1
    PyMySQL 可以,看最 Readme 的例子:
    https://github.com/PyMySQL/PyMySQL
    billlee
        2
    billlee  
       2016-03-18 20:35:00 +08:00
    mysqlclient
    pc10201
        3
    pc10201  
    OP
       2016-03-18 20:38:11 +08:00
    @billlee 我安装了这个,找没到相关的范例,能给个 demo 吗?
    lynx
        4
    lynx  
       2016-03-18 20:44:00 +08:00
    billlee
        5
    billlee  
       2016-03-18 22:12:35 +08:00
    @pc10201 API 和 mysql-python 完全一样,上面的代码完全不用改
    likuku
        6
    likuku  
       2016-03-18 22:15:30 +08:00
    python3 还在不断变化,较早版本的 3 ,装个 mysql 模块都不容易...
    zog
        7
    zog  
       2016-03-18 22:19:25 +08:00
    torndb
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2861 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 13:12 · PVG 21:12 · LAX 06:12 · JFK 09:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.