2011-05-13 109 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]