【发布时间】:2011-08-24 23:40:28
【问题描述】:
我正在使用 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。如果有提交的行,那么我可以获得列名列表。
还有其他方法吗?我通过了官方sqlite3module 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对象的.description字段c.execute('select * from stocks') r=c.fetchone() print c.description
其中,No.2 似乎是最简单和最直接的。谢谢大家的帮助。
【问题讨论】: