看flask的例子,从数据库获得数据是这样写的
cur = g.db.execute('''select a,b,c from user ''',[session['user_id']])
members = [dict(a=row[0], b=row[1],
c=row[2]) for row in cur.fetchall()]
感觉这样写row[*]好烦,能不能直接将列名写到字典里呢?
select * 并不这么影响的,感觉写起来很烦。
我目前只会直接写SQL语句,还没用到SQLAlchemy,SQLAlchemy具体优势有多少
cur = g.db.execute('''select a,b,c from user ''',[session['user_id']])
members = [dict(a=row[0], b=row[1],
c=row[2]) for row in cur.fetchall()]
感觉这样写row[*]好烦,能不能直接将列名写到字典里呢?
select * 并不这么影响的,感觉写起来很烦。
我目前只会直接写SQL语句,还没用到SQLAlchemy,SQLAlchemy具体优势有多少
8 条回复 • 1970-01-01 08:00:00 +08:00
|
1
cloud_dai 2011 年 12 月 6 日
你想直接用MySQLdb?
import MySQLdb import MySQLdb.cursors db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test',cursorclass = MySQLdb.cursors.DictCursor) cursor = db.cursor() cursor.execute('select * from user') rs = cursor.fetchall() #结果 # ({'name': "cloud", 'cash': 1000L}, {'name': "luce", 'cash': 2000L}, ...) #也可以这样 db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '123456', db = 'test') cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor) #具体的指南 http://mysql-python.sourceforge.net/MySQLdb.html |
|
2
linnchord 2011 年 12 月 6 日
你获取到的结果集应该包含列的名称,你可以遍历生成一个dict的列表。SQLAlchemy生成结果你可以简单认为是一个对象列表,上面的row转换为具体的数据表对应定义的对象。
|
|
3
cloud_dai 2011 年 12 月 6 日
至于SQLAlchemy, 它是个好东西!
除非你的SQL写的优化程度超过SQLAlchemy的机制的, 或很小的任务,也没必要另外装个package。 可以看看它的手册 http://www.sqlalchemy.org/docs/ |
|
5
SErHo 2011 年 12 月 6 日
推荐一个非常小巧的ORM,https://github.com/coleifer/peewee
|
|
7
loading OP |
推荐学习书目
› 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