我正在使用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