【问题标题】:Get list of column names from an empty table [duplicate]从空表中获取列名列表[重复]
【发布时间】: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,但在这方面找不到任何有用的东西。

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

编辑:

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

  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 对象的.description 字段

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

其中,No.2 似乎是最简单和最直接的。谢谢大家的帮助。

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    尝试:

    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 元组的第一项是有用的。

    【讨论】:

    • select ... limit 1,不是吗?
    【解决方案2】:
    import sqlite3
    con=sqlite3.connect(":memory:")
    c=con.cursor()
    c.execute("select * from stocks")
    fieldnames=[f[0] for f in c.description]
    

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 2013-09-15
      • 2022-07-09
      • 1970-01-01
      • 2011-05-09
      • 2017-12-15
      • 2021-10-18
      • 2020-11-23
      • 2010-12-22
      相关资源
      最近更新 更多