1
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 3 years have passed since last update.

データベースを作る。 (sqlite3)

Last updated at Posted at 2021-10-24

#はじめに
sql文が苦手なので、せめてデータベースの作成と読み込みの関数だけ作る。

#コード

main.py
import sqlite3


def makeDB(db,table_name,columns,cols):
#columns={<typename>:<type>,...}
        size=len(columns)
        cur=db.cursor()
        columns=",".join(map(lambda key:key+" "+columns[key],columns))
        cur.execute("create table if not exists {0} ({1})".format(table_name,columns))
        hatenas=",".join(["?"]*size)
        for col in cols:
                try:
                        cur.execute("insert into {0} values ({1})".format(table_name,hatenas),col)
                        db.commit()
                except Exception as e:
                        pass


def readDB(db,table_name):
        cur=db.cursor()
        return db.execute("select * from {0}".format(table_name))

#使う

a.csv
Natsumi;40;152;83;60;80
Sayaka;37;158;80;60;87
Maki;36;158;83;60;88
Mari;38;144;75;60;80
Rika;36;157;78;60;84
main.py
def readcsv(fname,encoding="utf8"):
        with open(fname,"r",encoding=encoding) as f:
                for line in f:
                        yield line.rstrip().split(";")

db=sqlite3.connect("a.db")
columns={"name":"text unique","age":"int","tall":"int","T":"int","W":"int","H":"int"}
fname="a.csv"
makeDB(db,"MM",columns,readcsv(fname))
for col in readDB(db,"MM"):
        print(col)
db.close()
実行結果
$ python main.py
('Natsumi', 40, 152, 83, 60, 80)
('Sayaka', 37, 158, 80, 60, 87)
('Maki', 36, 158, 83, 60, 88)
('Mari', 38, 144, 75, 60, 80)
('Rika', 36, 157, 78, 60, 84) 

#おわりに

些細なものだが、sql文を見なくて済むのは嬉しい。しかしいずれは見る羽目になるか。(笑)

1
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
1
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?