I am Charmie

メモとログ

SQLAlchemy: Workint with Data

このチュートリアルだけど,3個のサブセクションに分かれてる. このチュートリアルでは,前の2つのチュートリアルを基に関係データベース内でのデータの生成・選択・操作方法を学ぶ. データベースとのやり取りは常にトランザクションという形で行う.

  • stmtは多分statementの省略形かな.
  • そもそもuser_tableはどうやって宣言してたっけ?

Inserting Rows with Core

from sqlalchemy import insert
# Insert型インスタンスを生成
stmt = insert(user_table).values(name='spongebob', fullname="Spongebob Squarepants")
# insertの実行
with engine.connect() as connection:
    result = connection.execute(stmt)
    connection.commit()

# 複数のinsertを実行
with engine.connect() as connection:
    result = connection.execute(
        insert(user_table),
        [
            {"name": "sandy", "fullname": "Sandy Cheeks"},
            {"name": "patrick", "fullname": "Patrick Star"}
        ]
    )
    connection.commit()

Selecting Rows with Core or ORM

使う予定がないから飛ばす

from sqlalchemy import select
stmt = select(user_table).where(user_table.c.name == 'spongebob')
with engine.connect() as connection:
    for row in connection.execute(stmt):
        print(row)

Updating and Deleting Rows with Core

update()

  • update()は,テーブル中の既存データを更新するためのUpdate型インスタンスを生成
  • テーブルを指定
  • .where()で条件を指定
  • .values()で更新後の値を指定
from sqlalchemy import update
stmt = (
    update(user_table).where(user_table.c.name == 'patrick').
    values(fullname='Patrick the Star')
)
>>> print(stmt)

以下のように,まとめて複数件の更新もできる

from sqlalchemy import bindparam
stmt = (
  update(user_table).
  where(user_table.c.name == bindparam('oldname')).
  values(name=bindparam('newname'))
)
with engine.begin() as conn:
  conn.execute(
      stmt,
      [
         {'oldname':'jack', 'newname':'ed'},
         {'oldname':'wendy', 'newname':'mary'},
         {'oldname':'jim', 'newname':'jake'},
      ]
  )

delete()

  • delete()は,テーブル中の(複数の)行を削除するためのDelete型インスタンスを生成
from sqlalchemy import delete
stmt = delete(user_table).where(user_table.c.name == 'patrick')
print(stmt)