Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【python3】既存のsqlite3データベースをpython3で読み込む

まずはテーブル名を取得する

teminalで

sqlite3 something.db
sqlite> .table
で表示するのが通常の方法

pythonだけでもテーブル名は見れる

■ 参考 : pythonでsqliteのテーブル名取得

import sqlite3
filepath="something.db"
conn = sqlite3.connect(filepath)
cur = conn.cursor()

# table一覧を取得する
tables=[]
cur.execute("select name from sqlite_master where type='table'")
for catalog in cur.fetchall():
 tables.append(catalog[0])
print(tables)

cur.close()
conn.close()

みたいな感じ



テーブル名がわかったら、次はそのデータをリストに代入する

import sqlite3
import numpy as np
filepath="something.db"
conn = sqlite3.connect(filepath)
cur = conn.cursor()

# table hogehoge を読み込む
cur.execute("select * from hogehoge")
list_h = cur.fetchall()
# transposed
list_h_T = (np.array(list_h)).T

cur.close()
conn.close()

list_hにhogehogeの中身をすべて代入する
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
みたいな感じで、リストの中にタプルが入っている
このままやとすごく使いにくいので、まずnp.arraryでarray型に変換する
その後で転置すると、

[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

みたいな感じになる
これで list[1] をプロットすると元データのタプルの1列目をプロットすることができる


■ 参考 : Python: plot list of tuples




hogehogeというテーブルのカラム名を取り出したいとき

cur.execute("PRAGMA TABLE_INFO(hogehoge)")
cols = cur.fetchall()
# Pick up column name
col_si = [item[1] for item in cols]
print(col_si)

ランキング参加中です

↓クリックしていただけると嬉しいです〜