有没有办法获取 sqlite 中的列名列表?
- 2025-04-16 08:58:00
- admin 原创
- 16
问题描述:
我想从数据库中的表中获取列名列表。使用 pragma 时,我得到了一个包含大量不必要信息的元组列表。有没有办法只获取列名?所以我可能会得到这样的结果:
[列 1,列 2,列 3,列 4]
我绝对需要这个列表的原因是因为我想在列表中搜索一个列名并获取索引,因为索引在我的很多代码中都有使用。
有没有办法获得这样的列表?
谢谢
解决方案 1:
您可以使用 sqlite3 和pep-249
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from bar')
cursor.description是一个由 7 项序列组成的序列,其第一个元素是列名:
names = list(map(lambda x: x[0], cursor.description))
或者,您可以使用列表推导:
names = [description[0] for description in cursor.description]
解决方案 2:
smallredstone的cursor.description解决方案的替代方法是使用row.keys():
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row
cursor = connection.execute('select * from bar')
# instead of cursor.description:
row = cursor.fetchone()
names = row.keys()
缺点:只有当查询返回至少一行时它才有效。
好处:您可以通过列名访问列(row['your_column_name'])
在 python 文档中阅读有关 Row 对象的更多信息。
解决方案 3:
据我所知,Sqlite 不支持 INFORMATION_SCHEMA。它使用的是 sqlite_master。
我认为你无法仅用一个命令就获得你想要的列表。你可以使用 SQL 或 Pragma 获取所需的信息,然后使用正则表达式将其拆分成你需要的格式。
SELECT sql FROM sqlite_master WHERE name='tablename';
给你类似的东西
CREATE TABLE tablename(
col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
col2 NVARCHAR(100) NOT NULL,
col3 NVARCHAR(100) NOT NULL,
)
或者使用 pragma
PRAGMA table_info(tablename);
给你类似的东西
0|col1|INTEGER|1||1
1|col2|NVARCHAR(100)|1||0
2|col3|NVARCHAR(100)|1||0
解决方案 4:
您可以通过运行以下命令获取列名列表:
SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name
tbl_name
rootpage
sql
您可以通过运行以下命令来检查某一列是否存在:
SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1
参考:
https://www.sqlite.org/pragma.html#pragfunc
解决方案 5:
以快速、交互的方式查看列名
如果您在 Python 中以交互方式工作并且只想快速“查看”列名,我发现 cursor.description 可以起作用。
import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description
输出如下内容:
(('Date', None, None, None, None, None, None),
('Object-Name', None, None, None, None, None, None),
('Object-Count', None, None, None, None, None, None))
或者,快速访问并打印出来。
colnames = cursor.description
for row in colnames:
print row[0]
输出如下内容:
Date
Object-Name
Object-Count
解决方案 6:
这很简单。
首先创建一个连接,并将其命名为con
。然后运行以下代码。
cur =con.cursor()
cur.execute("select * from table_name limit 1")
col_name=[i[0] for i in cur.description]
print(col_name)
您将获得列表形式的列名
解决方案 7:
假设您知道表名,并且想要数据列的名称,您可以使用列出的代码以简单而优雅的方式按照我的口味完成它:
import sqlite3
def get_col_names():
#this works beautifully given that you know the table name
conn = sqlite3.connect("t.db")
c = conn.cursor()
c.execute("select * from tablename")
return [member[0] for member in c.description]
解决方案 8:
好吧,我可能回答这个问题已经很晚了,但是因为人们仍然关注这个话题,所以我只想分享我如何使用来获取列名列表python sqlite3
。
import sqlite3
def getVarList(con, tableName)
return [fields[1] for fields in con.execute(f"PRAGMA table_info({tableName})").fetchall()]
conn = sqlite3.connect('foo.db')
varList = getVarList(conn, 'bar')
解决方案 9:
我用的是这个:
import sqlite3
db = sqlite3.connect('~/foo.sqlite')
dbc = db.cursor()
dbc.execute("PRAGMA table_info('bar')"
ciao = dbc.fetchall()
HeaderList=[]
for i in ciao:
counter=0
for a in i:
counter+=1
if( counter==2):
HeaderList.append(a)
print(HeaderList)
解决方案 10:
我喜欢 @thebeancounter 的答案,但我更喜欢参数化未知参数,唯一的问题是表名容易被利用。如果你确定没问题,那么这样做可行:
def get_col_names(cursor, tablename):
"""Get column names of a table, given its name and a cursor
(or connection) to the database.
"""
reader=cursor.execute("SELECT * FROM {}".format(tablename))
return [x[0] for x in reader.description]
如果有问题,您可以添加代码来清理表名。
解决方案 11:
由于问题带有 Python 标记,我可以随意发布一个使用 Pandas 的 Python 特定答案:
import sqlite3
import pandas as pd
path_to_db = 'path/to/db'
connect = sqlite3.connect(path_to_db, isolation_level=None)
table = 'table_name'
column_list = list(pd.read_sql_query(f"SELECT * FROM {table} limit 1", connect).columns)
解决方案 12:
import sqlite3
with sqlite3.connect('statics.db') as cur:
cur.execute("CREATE TABLE IF NOT EXISTS data(id INT PRIMARY KEY NOT NULL)")
pragmas = cur.execute("PRAGMA table_info(data);")
columns = [n for _, n, *_ in pragmas.fetchall()]
print(columns)
解决方案 13:
使用 pragma 的另一种方法:
> table = "foo"
> cur.execute("SELECT group_concat(name, ', ') FROM pragma_table_info(?)", (table,))
> cur.fetchone()
('foo', 'bar', ...,)
解决方案 14:
如果您可以接受使用pandas
,我建议pandas.read_sql_query
您使用,它将返回一个完整的 DataFrame,包括列名作为标题;这也可以很好地格式化为标准输出。
import pandas as pd
import sqlite3
with sqlite3.connect("my_db_file.db") as conn:
df = pd.read_sql_query("SELECT * FROM foo", conn)
print(df) # use df.columns.tolist() for only the header
解决方案 15:
有点晚了,但这就是我想出的解决方案,依靠@flokk 的回答。
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row # this bit is important!!!!!
cursor = connection.cursor()
data = [dict(zip(x.keys(), x)) for x in cursor.execute('select * from bar').fetchall()]
print(data) # [{'col1': 'data1', 'col2': ...}, ...]
效率高吗?不。有用吗?是的!
我试图解决的问题是我不知道表的列是什么,这对我有很大帮助。
扫码咨询,免费领取项目管理大礼包!