※この記事は2020年に作成しました
やりたかったこと
麻雀の手牌(34種類)のリストをDBに入れて、CSVをかませずに直接PythonでDBから読み込む。
SQLite3ではリストを入れることはできないのが大変なポイント。
#作成したコード
# coding: UTF-8
import sqlite3
#sqliteにはリスト型が存在しないため、str型にして格納する\
def tehai_to_string(tmp):
tmp = [int(s) for s in tmp]
string = ''
for c in range(34):
string+=str(tmp[c])
return string
listDB =[0,0,0,2,0,0,0,3,0,0,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0]
listDB=tehai_to_string(listDB)
#print(Stehai)
conn = sqlite3.connect('test.sqlite3')
c = conn.cursor()
c.executescript("""
DROP TABLE IF EXISTS test;
CREATE TABLE test(tehai text)
""")
c.execute("insert into test values (?)", (Stehai,))
c.execute('select * from test')
data = c.fetchall()
print(data)
conn.commit()
conn.close()
##実行結果
[('0002000300000011100111011000000000',), ('0002000300000011100111011000000000',)]
#文字列に変換する
sqliteにはリスト型が存在しないので、リストを文字列に変換してから、文字列としてデータベースに入れている。
DBにはタプルで入れる。
#読み込み
# coding: UTF-8
import sqlite3
conn = sqlite3.connect('test.sqlite3')
c = conn.cursor()
for row in c.execute('select * from test'):
t = list(row)
tehai =[]
for i in t:
tehai += i
tehai = [int(s) for s in tehai]
print(tehai)
##実行結果
[0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#文字列から数値へ変換して取り出す
DBから取り出したデータはタプルなので、リストに変換してから、strの数字をintの数値に変換している。