[Python] Python から SQLite を操作する

  • 2022年9月18日
  • 2022年9月18日
  • Python
  • 9View
  • 0件

はじめに

SQLite は、単体アプリケーションで利用することを想定したデータベースです。
多くのデータベースとは異なり、サーバとしては動作せず、アプリケーションのプロセスに閉じて動作するデータベースになります。

SQLite データベースを操作

Python では SQLite を操作するための機能が標準ライブラリに組み込みされています。
Python3 さえ入っていればデータベースの読み書きが可能です。

サンプルコード

以下サンプルコードです。

import sqlite3

connection = sqlite3.connect("sample.db")
cursor = connection.cursor()
cursor.execute("create table address (name text, phone text)")
cursor.execute("insert into address values('山田', '090-xxxx-xxxx')")
connection.commit()

response = cursor.execute("select * from address")
print(response.fetchone())
connection.close()

sqlite3 のパッケージは標準ライブラリです。

sample.db のファイルをデータベースとして扱います。
事前に作成する必要はなく、ライブラリによって勝手に生成されます。

サンプルコードでは、address テーブルを生成し、これに山田の電話番号を登録し、最後にレコードを select します。

$ python3 main.py
('山田', '090-xxxx-xxxx')

なお、コード中にはテーブルの作成が含まれますので、2回連続で実行しようとするとテーブルの作成エラーが発生します。
5~6行目をコメントアウトすれば、select 結果の取得のみとなり正常終了します。

$ python3 main.py
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    cursor.execute("create table address (name text, phone text)")
sqlite3.OperationalError: table address already exists

公式ドキュメント

標準ライブラリなので公式ドキュメントがあります。