Python 从空表中获取列名列表
我正在使用Python的Python 从空表中获取列名列表,python,sqlite,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)'
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
,但在这方面找不到任何有用的东西
我想我可以在表中放入一些虚拟数据,然后检索列名,然后删除行,但我希望有一种更优雅的方法来实现这一点
编辑:
似乎有几种方法可以做到这一点:
c.execute("""SELECT sql FROM sqlite_master
WHERE tbl_name = 'stocks' AND type = 'table'""")
PRAGMA
语句:
c.execute("PRAGMA table_info(stocks)")
光标
对象的.description
字段
c.execute('select * from stocks')
r=c.fetchone()
print c.description
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))
如前所述,只有每个7元组的前几项是有用的。
选择。。。限制1
,否?
import sqlite3
con=sqlite3.connect(":memory:")
c=con.cursor()
c.execute("select * from stocks")
fieldnames=[f[0] for f in c.description]