我正在使用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()
Run Code Online (Sandbox Code Playgroud)
然后我可以用类似的东西获得列名
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from stocks')
r = c.fetchone()
print r.keys()
Run Code Online (Sandbox Code Playgroud)
问题是,如果表最初为空,则c.fetchone()返回None.如果有提交的行,那么我可以获得列名列表.
还有另一种方法吗?我浏览了官方sqlite3 模块文档,但在这方面找不到任何有用的东西.
我想我可以在表中放入一些虚拟数据,然后检索列名,然后删除该行,但我希望有一种更优雅的方式来做到这一点.
编辑:
似乎有几种方法可以做到:
获取用于创建表的SQL:
c.execute("""SELECT sql FROM sqlite_master
WHERE tbl_name = 'stocks' AND type = 'table'""")
Run Code Online (Sandbox Code Playgroud)使用PRAGMAsqlite3中的语句:
c.execute("PRAGMA table_info(stocks)")
Run Code Online (Sandbox Code Playgroud)使用对象的.description字段Cursor
c.execute('select * from stocks')
r=c.fetchone()
print c.description
Run Code Online (Sandbox Code Playgroud)其中,No.2似乎是最简单和最直接的.谢谢大家的帮助.
尝试:
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))
Run Code Online (Sandbox Code Playgroud)
正如解释在这里,只有每个7元组的第一项是有用的.
| 归档时间: |
|
| 查看次数: |
13138 次 |
| 最近记录: |