python sqlalchemy 动态获取列名?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
connection = create_engine('mysql://user:passwd@localhost:3306/db').connect()
result = connection.execute("select * from table")
for v in result:
print v['id']
print v['name']
connection.close()
我如何动态获取表列名称?在本例中 id
和 name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过调用
result.keys()
查找列,也可以通过在for
循环内调用v.keys()
来访问它们。以下是使用
items()
的示例:You can either find the columns by calling
result.keys()
or you can access them through callingv.keys()
inside thefor
loop.Here's an example using
items()
:最直接的解决方案
没有比使用列表理解的单行解决方案更简单的了。这也是最直接的方法:
@Saul 的答案也有效,但是您需要小心仅迭代每个
cursor.description
的第一个元素,以免得到一堆。
它的效率也较低,因为您需要遍历 ResultProxy,访问 cursor.description 属性,并且每个属性仅检索索引 0 处的元素
。 Python 中的
timeit
经过 500,000 次迭代显示了速度差异(0.016 与 0.011):虽然建议的解决方案完成时间减少了约 30%:
事实上,我怀疑时间在具有更多列的表上,差异可能比上面明显简化的示例更大。
实践中:键和值
在实践中,您可能希望动态打印键和值。有两种方法可以解决这个问题。第一种:
或者使用解包:
这两种方法都是直接的和Pythonic的,同时也使程序员不必显式指定(或事先知道)列名称。
Most direct solution
Can't get any simpler than a one-liner solution using list comprehension. It also is the most direct method:
@Saul's answer also works, but you'll need to be careful about iterating over only the first element through each
cursor.description
, lest you get a bunch ofNone
in each tuple of the returned list.It also is less-efficient, because you need to iterate through the
ResultProxy
, access thecursor.description
attribute and for each of them only retrieve the element at index 0.Using
timeit
in Python with 500,000 iterations showed the speed difference (0.016 vs 0.011):While the proposed solution completes in ~30% less time:
In fact, my suspicion is that the time difference could be greater on a table with more columns than the obviously simplified example above.
In Practice: keys and values
In practice, you'd probably want to print both the key and values dynamically. There are two ways you can go about it. The first:
Alternatively using unpacking:
Both of these methods are direct and pythonic, while also exempt the programmer from having to specify (or know beforehand) the columns names explicitly.
像这样的
headers=[ i[0] for i in result.cursor.description ]
这里有同样的问题 从 pyodbcexecute() 语句返回列名称
something like this
headers=[ i[0] for i in result.cursor.description ]
same question here return column names from pyodbc execute() statement