获取空表中的列名列表

时间:2011-05-13 14:05:20

标签: python sqlite

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

我想我可以在表中放入一些虚拟数据,然后检索列名然后删除该行,但我希望有更优雅的方法来实现它。

修改

似乎有几种方法可以做到:

  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. 使用.description对象

    Cursor字段
    c.execute('select * from stocks')
    r=c.fetchone()
    print c.description
    
  4. 其中,No.2似乎是最简单,最直接的。谢谢大家的帮助。

2 个答案:

答案 0 :(得分: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元组的第一项才有用。

答案 1 :(得分:3)

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