備忘録

備忘録

PythonでSQLiteを使う方法

Ⅰ. はじめに

Python の sqlite3 は標準ライブラリです。
pipからインストールする必要はありません。

Ⅱ. サンプルプログラム

#!/usr/bin/env python3
# coding: utf-8
import sqlite3

conn = sqlite3.connect('main2.sqlite3')
c = conn.cursor()

# create table
c.execute('create table `accounts` (`id` integer, `name` text)')
# conn.commit()

# insert
data = [
  (1, 'name001'),
  (2, 'name002'),
  (3, 'name003')
]
c.executemany("insert into accounts values(?, ?)", data)
conn.commit()

# select
for row in c.execute('select * from accounts'):
  print(row)

conn.close()

実行結果

(1, 'name001')
(2, 'name002')
(3, 'name003')