Python 查询 SQLite 将值映射到列名

pen*_*ngz 2 python database sqlite json object

我正在创建一个 python 脚本来查询 SQLite DB 文件。我已连接到 SQLite db 文件并运行 SELECT 查询来检索数据。

问题是输出缺少列名。

import sqlite3 as lite
import sys
import json

con = lite.connect('example.db')

with con:

        con.row_factory = lite.Row

        cur = con.cursor()
        cur.execute("SELECT * FROM Devices")

        rows = cur.fetchall()

        rowarray_list = []
        for row in rows:
                t = (row['id'], row['name'], row['type'])
                rowarray_list.append(t)

        j = json.dumps(rowarray_list)
        rowarrays_file = 'rowarrays.js'
        f = open(rowarrays_file,'w')
        print (f, j)
Run Code Online (Sandbox Code Playgroud)

这是脚本的输出。

<_io.TextIOWrapper name='rowarrays.js' mode='w' encoding='UTF-8'> [[1, "example1", "Computer"], [2, "example2", "Server"], [3, "example3", "Server"]
Run Code Online (Sandbox Code Playgroud)

以下是所需的输出。

{"records":[{"id": "1", "name": "example1", "type": "Computer"}, {"id": "2", "name": "example2", "type": "Server"}, {"id": "3", "name": "example3", "type": "Server"}]}
Run Code Online (Sandbox Code Playgroud)

gil*_*gil 6

由于您已经在使用sqlite3.Row对象,您可能知道它们有一个keys()方法,它返回一个列名列表。用那个。尝试修改这部分代码:

rowarray_list = []
for row in rows:
    d = dict(zip(row.keys(), row))   # a dict with column names as keys
    rowarray_list.append(d)
Run Code Online (Sandbox Code Playgroud)