使用Python sqlite3 API列出表、数据库架构、转储等

208 投票
12 回答
289121 浏览
提问于 2025-04-11 18:46

出于某种原因,我找不到获取sqlite交互式命令等效方法的办法:

.tables
.dump

使用Python的sqlite3接口。

有没有类似的东西呢?

12 个回答

96

在Python中,最快的方法是使用Pandas库(版本0.16及以上)。

如果你想导出一张表,可以使用:

db = sqlite3.connect('database.db')
table = pd.read_sql_query("SELECT * from table_name", db)
table.to_csv(table_name + '.csv', index_label='index')

如果你想导出所有的表,可以使用:

import sqlite3
import pandas as pd


def to_csv():
    db = sqlite3.connect('database.db')
    cursor = db.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    for table_name in tables:
        table_name = table_name[0]
        table = pd.read_sql_query("SELECT * from %s" % table_name, db)
        table.to_csv(table_name + '.csv', index_label='index')
    cursor.close()
    db.close()
340

在Python中:

con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())

注意查看我其他的回答。有一种使用pandas的方法更快。

111

你可以通过查询 SQLITE_MASTER 表来获取数据库中所有表格和结构的信息:

sqlite> .tab
job         snmptarget  t1          t2          t3        
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3

sqlite> .schema job
CREATE TABLE job (
    id INTEGER PRIMARY KEY,
    data VARCHAR
);
sqlite> select sql from sqlite_master where type = 'table' and name = 'job';
CREATE TABLE job (
    id INTEGER PRIMARY KEY,
    data VARCHAR
)

撰写回答