2
2

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

sqlite3へのデータINSERT by python

Posted at

作成した喫茶店リストをDBに追加する

データカラムは
(id,title,住所、作成日、作成者、カテゴリー)の6要素
なので

ids=[]
for i,(name,address,date,author,category) in enumerate(zip(titles,adresses,dates,authors,categorys),1):
    id=(i,name,address,date,date,author,category)
    ids.append(id)

6つの引数を持つリストを作成(あらかじめdates,authors,categoryのタプルは作成済み)

ここからDB操作

テーブル名がわからないので

import sqlite3

sqlite_path = ""
connection = sqlite3.connect(sqlite_path)
cursor = connection.cursor()

cursor.execute("SELECT*FROM sqlite_master where type='table'")
for x in cursor.fetchall():
    print(x)

上記のコードでテーブル名を取得
得たテーブル名で改めてデータを挿入する

sqlite_path = ""
connection = sqlite3.connect(sqlite_path)
cursor = connection.cursor()

try:
    cursor.executemany("INSERT INTO talbe_name VALUES(?,?,?,?,?,?)",ids)
    connection.commit()


except sqlite3.Error as e:
    print('sqlite3.Error occurred:', e.args[0])
    
cursor.execute('SELECT*FROM table_name')
res=cursor.fetchall()
print(res)



connection.close()

ポイント
・try exceptでエラーをキャッチできるようにする
・VALUES()でカラム数を定義する
・複数なのでexecute()ではなくexecutemany()を用いる。
・commitし、DBへ保存
・DBへアクセスし、データを確認

おまけメモ
SELECT id, name FROM table
⇒id nameが返される

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?