サンプル集  >  Python  >  PostgreSQL sqlalchemy 検索
PostgreSQL sqlalchemy 検索
2023/05/21

MySQLへsqlalchemyでレコードを検索します。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Python 3.9.6
VS Code 1.59.0

PostgreSQL sqlalchemy 追加で作成したaisatsuテーブルのレコードを検索するプログラムを作成します。

psqlSel.py
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
from sqlalchemy import create_engine, desc
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String

db_url="postgresql://" \
       "user:pass@localhost:5432/mydb"

engine = create_engine(db_url)

db_session = scoped_session(
    sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=engine
    )
)

Base = declarative_base()
Base.query = db_session.query_property()

class aisatsu(Base):
    __tablename__ = "aisatsu"

    id = Column(Integer, primary_key = True, autoincrement=True)
    text = Column(String, unique=False)

    def __init__(self, text):
        self.text = text

print("(1) ALL")
rslt = db_session.query(aisatsu).all()
for row in rslt:
    print(row.text)

print("(2) id==2")
rslt = db_session.query(aisatsu).filter(aisatsu.id == 2).all()
for row in rslt:
    print(row.text)

print("(3) limit 2")
rslt = db_session.query(aisatsu).limit(2).all()
for row in rslt:
    print(row.text)

print("(4) order by id desc")
rslt = db_session.query(aisatsu).order_by(desc(aisatsu.id)).all()
for row in rslt:
    print(row.text)

MySQLのプログラムのdb_urlだけ変更しました。

実行してみます。

PS C:\pywork> py .\psqlSel.py
(1) ALL
こんにちわ
おはよう
Hello
(2) id==2
おはよう
(3) limit 2
こんにちわ
おはよう
(4) order by id desc
Hello
おはよう
こんにちわ

期待通りにデータの検索ができました。

▲ PageTop  ■ Home


Copyright (C) 2023 ymlib.com