LoginSignup
0
0

SQLAlchemy: MariaDB のデータを読む (Read)

Last updated at Posted at 2022-04-19

プログラム

maria_read.py
#! /usr/bin/python
#
#	maria_read.py
#					Apr/19/2022
#
# ----------------------------------------------------------------
import sys
#
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, Sequence
from sqlalchemy.orm import scoped_session, sessionmaker
#
# ----------------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")
#
host='localhost'
data_base = 'city'
user ='scott'
password = 'tiger123'
db_url = "mysql://" + user + ":" + password + "@" + host + "/" + data_base
engine = create_engine(db_url)
#
Base = declarative_base()
class City(Base):
	__tablename__ = "cities"
	id = Column(String(16), primary_key=True)
	name = Column(String(255))
	population = Column(Integer)
	date_mod = Column(DateTime)
#
#

session = scoped_session(
	sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
#
cities = session.query(City).all()
for city in cities:
	print(f'{city.id}\t{city.name}\t{city.population}\t{city.date_mod}')

sys.stderr.write ("*** 終了 ***\n")
#
# ----------------------------------------------------------------

実行コマンド

./maria_read.py

確認したバージョン

$ python --version
Python 3.11.3
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0