SQLAlchemyでHello World (ORマッピング)

Python 3.8.10
psycopgが必要。

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

db_string = "postgresql://user:password@localhost:5432/testdb"

db = create_engine(db_string)
base = declarative_base()

# ORマッピング
class Hello(base):
    __tablename__ = 'hello'

    id = Column(Integer, primary_key=True)
    msg = Column(String)

Session = sessionmaker(db)
session = Session()

# テーブルが存在しなければ作成。
base.metadata.create_all(db)

# INSERT
data = Hello(msg="Hello World!")
session.add(data)
session.commit()

# SELECT
select = session.query(Hello)
for row in select:
    print(row.msg)

# UPDATE
data.msg = "Hello Wolrd! 2"
session.commit()

# SELECT
select = session.query(Hello)
for row in select:
    print(row.msg)

# Delete
session.delete(data)
session.commit()

実行結果

python test.py
Hello World!
Hello Wolrd! 2

作成されたテーブル

testdb=> \d hello;
                                 Table "public.hello"
 Column |       Type        | Collation | Nullable |              Default
--------+-------------------+-----------+----------+-----------------------------------
 id     | integer           |           | not null | nextval('hello_id_seq'::regclass)
 msg    | character varying |           |          |
Indexes:
    "hello_pkey" PRIMARY KEY, btree (id)

 

投稿日: