2011-05-13 165 views
8

我正在使用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,但在這方面找不到任何有用的東西。

我想我可以在表中放入一些虛擬數據,然後檢索列名,然後刪除行,但我希望有一個更優雅的方式來做到這一點。

編輯:

似乎有幾個方法可以做到這一點:

  1. 獲取用於創建表的SQL:

    c.execute("""SELECT sql FROM sqlite_master 
    WHERE tbl_name = 'stocks' AND type = 'table'""") 
    
  2. 使用來自sqlite3的聲明PRAGMA

    c.execute("PRAGMA table_info(stocks)") 
    
  3. 使用Cursor對象

    c.execute('select * from stocks') 
    r=c.fetchone() 
    print c.description 
    

其中的.description場,2號似乎是最簡單,最直接的。感謝所有的幫助。

回答

5

嘗試:

conn.row_factory = sqlite3.Row 
c = conn.cursor() 
c.execute('select * from stocks') 
r = c.fetchone() 
print c.description   # This will print the columns names 

>>> (('date', None, None, None, None, None, None), ('trans', None, None, None, None, None, None), ('symbol', None, None, None, None, None, None), ('qty', None, None, None, None, None, None), ('price', None, None, None, None, None, None)) 

如所解釋的here,只有每個7-元組的第一個項目是有用的。

+2

'select ... limit 1',no? – dan3 2014-08-19 13:47:38

3
import sqlite3 
con=sqlite3.connect(":memory:") 
c=con.cursor() 
c.execute("select * from stocks") 
fieldnames=[f[0] for f in c.description]