我有一個名為 art.db 的資料庫,它由 5 個表組成:表 1、表 2、表 3、表 4 和表 5
我想將 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 應包含 json 格式的所有 5 個表資料。
uj5u.com熱心網友回復:
您的問題缺乏可重現的資料,但您可以嘗試以下操作:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341404.html
