0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PythonでSQLite3を使ってデータベースにリストを入れる

Last updated at Posted at 2023-06-05

※この記事は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の数値に変換している。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?