0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2022-04-19

プログラム

maria_update.py
#! /usr/bin/python
#
#	maria_update.py
#					Sep/03/2024
#
# ----------------------------------------------------------------
import sys
from time import localtime,strftime
#
from sqlalchemy import create_engine
from sqlalchemy.orm 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'
# host='10.39.166.1'
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).filter_by(id=key_in).first()
	if city_a != None:
		city_a.population = population_in
		city_a.date_mod = strftime("%Y-%m-%d",localtime ())
		sys.stderr.write(key_in + " is updated.\n")
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?