[python]SQLite3のselect結果を辞書リストに変換する(自分メモ)

python

pythonでSlackbotを作ったときに内部のDBとしてSQLite3を採用した。

他のDBをpythonで扱ったことがないので知らないが、標準で入ってるsqlite3モジュールではselectした結果がタプルの配列で返ってくる。

これが別処理で使いづらく辞書リストにわざわざ変換してるのでその部分をメモがてら記事にしときます(元コードからパッチワークしたので動作未確認)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import sqlite3
import json
 
class SampleDB:
 
    def __init__(self):
        # データベースファイルのパス
        self.dbpath = 'C:\\work\\db.sqlite'
        # データベース接続とカーソル生成
        self.connection = sqlite3.connect(self.dbpath)
        self.connection.row_factory = sqlite3.Row
        self.cursor = self.connection.cursor()
 
    def _db_to_dictlist(self, rowdata):
        dictlist = []           # 空のリストを定義しとく
        for data in rowdata:    # rawdataはタプルのリスト
            cols = data.keys()  # DBのカラム値をリストで取得
            pos = 0
            json = {}
            for col in cols:    # DBのカラム値分タプルの内容を辞書型に挿入していく
                d = {col : data[pos]}
                json.update(d)
                pos += 1
 
            dictlist.append(json) # リストに追加
 
        return dictlist
 
    def release(self):
        self.connection.commit()
        self.connection.close()
 
 
test_db = SampleDB()
sql = f"SELECT * FROM sample_tbl"
test_db.cursor.execute(sql)
result = test_db.db_to_dictlist(test_db.cursor.fetchall())

んーしかしこの記事書くときに改めて調べてみると標準で辞書型のアクセスができそうな気がする・・・?

https://docs.python.org/ja/3/library/sqlite3.html#sqlite3.Row

まぁ今度確認してみよう。。。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA