0

我有一个名为 art.db 的数据库,它由 5 个表组成:table1、table2、table3、table4 和 table5

我想将所有表数据以 json 格式写入文本文件。我只能写一个表数据。有人可以帮我吗

下面是我的代码:

import json
import sqlite3
con = sqlite3.connect('/content/art.db')
cursor = con.cursor()

cursor.execute('''SELECT * FROM table1''')
rows = cursor.fetchall()

rowarray_list = []
for row in rows:
    t = (row[0], row[1])
    rowarray_list.append(t)

j = json.dumps(rowarray_list)

with open("table1.js", "w") as f:
    f.write(j)

import collections

objects_list = []
for row in rows:
    d = collections.OrderedDict()
    d["artwork_id"] = row[0]
    d["department_id"] = row[1]
    objects_list.append(d)

j = json.dumps(objects_list)

with open("final_data.txt", "w") as f:
    f.write(j)

final_data.txt 应该包含所有 5 个 json 格式的表数据。

4

1 回答 1

1

您的问题缺乏可重现的数据,但您可以尝试这样的事情:

import sqlite3
import json

# https://stackoverflow.com/a/3300514/15239951
def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

tables = ['table1', 'table2', 'table3', 'table4', 'table5']
data = {}

con = sqlite3.connect('/content/art.db')
con.row_factory = dict_factory
cursor = con.cursor()

for table in tables:
    cursor.execute(f'''SELECT * FROM {table}''')
    rows = cursor.fetchall()
    data[table] = rows

with open('final_data.json', 'w') as fp:
    json.dump(data, fp, indent=4)
于 2021-10-29T06:34:48.743 回答