有没有办法获取 sqlite 中的列名称列表?

发布于 2024-12-11 02:31:42 字数 228 浏览 0 评论 0原文

我想从数据库中的表中获取列名列表。使用 pragma 我得到了一个元组列表,其中包含很多不需要的信息。有没有办法只获取列名?所以我最终可能会得到这样的结果:

[列 1、列 2、列 3、列 4]

我绝对需要这个列表的原因是因为我想在列表中搜索列名并获取索引,因为索引在我的很多代码中使用。

有没有办法获得这样的列表?

谢谢

I want to get a list of column names from a table in a database. Using pragma I get a list of tuples with a lot of unneeded information. Is there a way to get only the column names? So I might end up with something like this:

[Column1, Column2, Column3, Column4]

The reason why I absolutely need this list is because I want to search for a column name in the list and get the index because the index is used in a lot of my code.

Is there a way of getting a list like this?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

四叶草在未来唯美盛开 2024-12-18 02:31:42

您可以使用 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]

You can use sqlite3 and pep-249

import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from bar')

cursor.description is a sequence of 7-item sequences whose first element is the column name:

names = list(map(lambda x: x[0], cursor.description))

Alternatively you could use a list comprehension:

names = [description[0] for description in cursor.description]
守护在此方 2024-12-18 02:31:42

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 文档中的行对象

An alternative to the cursor.description solution from smallredstone could be to use 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()

The drawback: it only works if there is at least a row returned from the query.

The benefit: you can access the columns by their name (row['your_column_name'])

Read more about the Row objects in the python documentation.

花落人断肠 2024-12-18 02:31:42

据我所知,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

As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.

I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need

SELECT sql FROM sqlite_master WHERE name='tablename';

gives you something like

CREATE TABLE tablename(
        col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        col2 NVARCHAR(100) NOT NULL,
        col3 NVARCHAR(100) NOT NULL,
)

Or using pragma

PRAGMA table_info(tablename);

gives you something like

0|col1|INTEGER|1||1
1|col2|NVARCHAR(100)|1||0
2|col3|NVARCHAR(100)|1||0
寂寞美少年 2024-12-18 02:31:42

查看列名称的快速交互式方式

如果您在 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

Quick, interactive way to see column names

If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.

import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description

Outputs something like this:

(('Date', None, None, None, None, None, None),
 ('Object-Name', None, None, None, None, None, None),
 ('Object-Count', None, None, None, None, None, None))

Or, quick way to access and print them out.

colnames = cursor.description
for row in colnames:
    print row[0]

Outputs something like this:

Date
Object-Name
Object-Count
请止步禁区 2024-12-18 02:31:42

您可以通过运行来获取列名称列表:

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

You can get a list of column names by running:

SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name      
tbl_name  
rootpage  
sql

You can check if a certain column exists by running:

SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1

Reference:

https://www.sqlite.org/pragma.html#pragfunc

捶死心动 2024-12-18 02:31:42

这很容易。
首先创建一个连接,我们将其命名为con
然后运行以下代码。

cur =con.cursor()
cur.execute("select * from table_name limit 1")
col_name=[i[0] for i in cur.description]
print(col_name)

您将获得列表形式的列名称

It is very easy.
First create a connection , lets name it, con.
Then run the following code.

cur =con.cursor()
cur.execute("select * from table_name limit 1")
col_name=[i[0] for i in cur.description]
print(col_name)

You will get column name as a list

夕嗳→ 2024-12-18 02:31:42

假设您知道表名称,并且想要数据列的名称,您可以使用列出的代码将以一种简单而优雅的方式完成它,符合我的口味:

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]

Assuming that you know the table name, and want the names of the data columns you can use the listed code will do it in a simple and elegant way to my taste:

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]
晨曦÷微暖 2024-12-18 02:31:42

好吧,我可能很晚才回答这个问题,但由于人们仍然关注这个线程,我只是想分享一下我如何使用 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')

Well, I may be very late to answer this but since people still follow this thread, I just wanted to share how I use to get the list of column names in 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')
平定天下 2024-12-18 02:31:42

我用这个:

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)

I use this:

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)
走走停停 2024-12-18 02:31:42

我喜欢@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] 

如果有问题,您可以添加代码来清理表名。

I like the answer by @thebeancounter, but prefer to parameterize the unknowns, the only problem being a vulnerability to exploits on the table name. If you're sure it's okay, then this works:

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] 

If it's a problem, you could add code to sanitize the tablename.

鲜肉鲜肉永远不皱 2024-12-18 02:31:42

因为这个问题有一个 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)

Since the question has a python flag. I feel free to post a python specific answer with pandas:

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)
迷荒 2024-12-18 02:31:42
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)
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)
芸娘子的小脾气 2024-12-18 02:31:42

使用 pragma 的另一种方法:

> table = "foo"
> cur.execute("SELECT group_concat(name, ', ') FROM pragma_table_info(?)", (table,))
> cur.fetchone()
('foo', 'bar', ...,)

Another way of using pragma:

> table = "foo"
> cur.execute("SELECT group_concat(name, ', ') FROM pragma_table_info(?)", (table,))
> cur.fetchone()
('foo', 'bar', ...,)
暮年慕年 2024-12-18 02:31:42

如果您喜欢使用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

If you are fine with using pandas, I recommend using pandas.read_sql_query, which will give you back a full DataFrame including the column names as header; this also nicely formats to stdout.

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
以酷 2024-12-18 02:31:42

聚会有点晚了,但这就是我想出的解决方案小猪后退 @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': ...}, ...]

有效率吗?不,有效果吗?是的!

我试图解决的问题是我不知道表的列是什么,这对我帮助很大。

Kinda late to the party, but this is what i came up with this solution piggy backing off @flokk answer.

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': ...}, ...]

is it efficient? No. Does it work? Yes!

The problem I was trying to solve was that I had no clue what the columns of the table were, and this helped me out immensely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文