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

【Python】【SQLite3】PythonでSQLiteを操作する(基本編)

Posted at

PythonでSQLiteを操作するときのメモ
備忘録です。
#ソースコードと説明

sample.py
import sqlite3
from contextlib import closing

dbname = "sample.db"

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()
    query = '''drop table if exists User'''
    c.execute(query)
    conn.commit()

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()
    query = '''create table if not exists
                User(id integer primary key, name varchar(32))'''
    c.execute(query)
    conn.commit()

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()
    query = ''' insert into User (id, name) values (?,?)'''
    user = (1, "Yamashita")
    c.execute(query, user)
    conn.commit()

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()
    query = ''' insert into User (id, name) values (?,?)'''
    user = [
        (2, "Kinoshita")
        ,(3, "Hasegawa")
    ]
    c.executemany(query, user)
    conn.commit()

with closing(sqlite3.connect(dbname)) as conn:
    c = conn.cursor()
    query = "select * from User"
    for row in c.execute(query):
        print(row)

##with closing(sqlite3.connect(dbname)) as conn:
sqliteを操作する際は、クエリの実行後commit(),close()が必要
contextlibのclosingを使用することで、connectionのclose()記載漏れを防げる

##c.executemany(query, user)
executemany()を使用すると、タプルのリストを引数として渡して複数のinsertをまとめて記述できる

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