はじまり

今回は、Pythonでsqlite3からCSVの文字列を出力するというテーマです。

なんで、こんな記事を書こうと思ったかというと、「sqlite csv」とググってもcsvをsqlite3のDBのテーブルに入れる記事ばっかりヒットしたからです(TへT)
その悲しさから、この記事を思いのまま勢いに任せて書いています!

もう、リサちゃんともペンギンとも話さずに間髪入れずに書いてしまうぞー!
sqlite to CSVの記事、スタート!
sqlite3の中のデータ確認!
今入っているテーブルとデータがまあこんな感じです。

実際にPythonでデータを取り出したいと思います!
こんな作業はさっさとjupyter notebookで取り出してしまいたいと思います。
あ~、久しぶりにPython触るなあ。自分が作ったプログラムからデータを取るから分かりやすいというのもあると思うんだが、やはりPythonは読みやすいと身にしみる。文法もちょっと予想で書けちゃったりするし。

と、思ってコード書いてたら、よく分からんエラーが出てきて、エラーコードも大して読まずに適当に直す。しかし、治らない・・・・。どういうこと!?
しょうがねえなあ、ちゃんと読むか・・・。
どれどれ、読んでみると、ん? もしかして、listをjoinした文字列にするのに、そのlistにintが入ってるとダメ? マジデ!? そっかー、最近SIer的なことしかやってないから、DBから取ってくるデータが文字列か数値型かなんていう思考が頭から抜けてしまっている~。

よし、型変換はしたぞ・・・でも、なんかNoneTypeもいる・・・。まあ、嫌な予感はするが、放っておくか・・・。

は? もう直したぞ。なのに、出力できないとはなにごと。

確かに、listの値は全て文字列(str)型になっている・・・。なぜだ・・・。
あ! list_jじゃなくて、jで出力してしまっている! intが入っているtupleのまんまだ!

よしよし・・・いい子だ・・・、list_jにしたらCSV出力できてるぜ。

よしよし、完全勝利かな~。これは。ガッハッハ~

ガッ!!!!! ハ~ッハッ!!!!!!!
あ~、やっぱりNoneTypeを無視してはならなかったか~。

ぬ~、これでは消えないのか~。

お! type判定じゃなくて、Noneかどうかを判定したほうが良いのか! strになった!
一応、最後のデータまで確認するかあ。またなんかあるとめんどいし。

うわああああ、やっぱりいやがった。floatかあ~。

うるせええ!!!
(デバッガ「バグを教えただけなのに・・・。。。」)

よーし、次こそは全部strになってる!

よーし、CSVで全部吐き出されたぞ~。

そして、これがGoogleスプレッドシートに問題なく貼り付けられるのかどうかをチェック。(テーブルの区切りをつけて貼りやすくする。)

よしよし、ちゃんと貼り付けられる。(エラーメッセージが出ている理由は、データ形式をシート上で変えてるからですね。今後使う型はbooleanなので。)

一番欲しかったデータも手に入った! (データ変えなきゃな。服のidじゃなくて、暖かさが欲しい。)
今回作ったコード
今回、sqlite3からCSVを作るために使ったコードはこれです。ファイル書き込み機能はありませんが、僕みたいにExcelとかGoogleスプレッドシート用に使う場合は、これを元にすれば事足りるはずです。
import sqlite3
dbpath = 'wwwardrobe.sqlite' # DB's path
connection = sqlite3.connect(dbpath)
cursor = connection.cursor()
tables = ['users', 'wardrobes', 'history_own', 'history_wear', 'weather_today']
for i in tables:
cursor.execute("SELECT * FROM {};".format(i))
rows = cursor.fetchall()
print(i + ' ------------------------------------------------------')
for j in rows:
j_list = list(j)
for k in range(len(j_list)):
if type(j_list[k]) is int:
j_list[k] = str(j_list[k])
elif j_list[k] is None:
j_list[k] = ""
elif type(j_list[k]) is float:
j_list[k] = str(j_list[k])
print(','.join(list(j_list)))
おしまい

ふ~、なんか勢いで書いてしまったな。まあ、JPEGminiの1日の無料分をここで良い感じに使い切れたし、良かった良かった。

ただいマンドラゴラ~。あー、お腹すいたー。

おかえリナインバース~。なんか勢い余ってるから、僕が料理するよ。

本当? ラッキー♪ じゃあ、私も勢い余って味噌汁作ろうかな・・・

それはダメだああああ!!!! 勢いを殺すぜ!!!!

・・・・・・はい

ただいまー!!! おれも勢いが余って、飼い主のメガネをかち壊しそうだ~~!!!

うるさい! ペギラマ!!

うわああああ!!! 勢いが足りなかったかああああ!!!!!
以上になります!
コメント