我正在使用Python的sqlite3
模块,并希望在表中没有任何行时获取表中所有列的列表。从空表中获取列名列表
通常情况下,如果我创建像
import sqlite3
conn = sqlite3.connect(":memory:")
c = conn.cursor()
# create the table schema
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
conn.commit()
c.close()
数据库然后,我可以得到的东西列名状
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from stocks')
r = c.fetchone()
print r.keys()
的问题是,如果表最初是空的,c.fetchone()
回报None
。如果有提交的行,那么我可以获得列名称的列表。
有没有另一种方法呢?我经历了官方sqlite3
module documentation,但在这方面找不到任何有用的东西。
我想我可以在表中放入一些虚拟数据,然后检索列名,然后删除行,但我希望有一个更优雅的方式来做到这一点。
编辑:
似乎有几个方法可以做到这一点:
获取用于创建表的SQL:
c.execute("""SELECT sql FROM sqlite_master WHERE tbl_name = 'stocks' AND type = 'table'""")
使用来自sqlite3的声明
PRAGMA
:c.execute("PRAGMA table_info(stocks)")
使用
Cursor
对象c.execute('select * from stocks') r=c.fetchone() print c.description
其中的.description
场,2号似乎是最简单,最直接的。感谢所有的帮助。
'select ... limit 1',no? – dan3 2014-08-19 13:47:38