Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从空表中获取列名列表_Python_Sqlite - Fatal编程技术网

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)'

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

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

编辑:

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

  • 获取用于创建表的SQL:

    c.execute("""SELECT sql FROM sqlite_master 
    WHERE tbl_name = 'stocks' AND type = 'table'""")
    
  • 使用sqlite3中的
    PRAGMA
    语句:

    c.execute("PRAGMA table_info(stocks)")
    
  • 使用
    光标
    对象的
    .description
    字段

    c.execute('select * from stocks')
    r=c.fetchone()
    print c.description
    
  • 其中,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))
    

    如前所述,只有每个7元组的前几项是有用的。

    选择。。。限制1
    ,否?
    import sqlite3
    con=sqlite3.connect(":memory:")
    c=con.cursor()
    c.execute("select * from stocks")
    fieldnames=[f[0] for f in c.description]