LoginSignup
0
0

SQLAlchemy: MariaDB のデータを更新 (Update)

Last updated at Posted at 2022-04-19

プログラム

maria_update.py
#! /usr/bin/python
#
#	maria_update.py
#					May/08/2023
#
# ----------------------------------------------------------------
import sys
from time import localtime,strftime
#
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")
#
key_in = sys.argv[1]
population_in = int(sys.argv[2])
print("%s\t%d" % (key_in, population_in))
#
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)
)
#
try:
        city_a = session.query(City).get(key_in)
        city_a.population = population_in
        city_a.date_mod = strftime ("%Y-%m-%d",localtime ())
except Exception as ee:
        sys.stderr.write(str(ee) + "\n")
session.commit()
#
sys.stderr.write ("*** 終了 ***\n")
#
# ----------------------------------------------------------------

実行コマンド

./maria_update.py t3328 89145700

確認したバージョン

$ 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