How to update with SQLAlchemy?

This time I will write the method of ** Update ** with ** SQLAlchemy **.

Operating environment

Sample code

Update the record of id == 2 (name = "Seiichi Sugino", kana ='Sugi no Seiichi').

sqlalchemy_update.py


# -*- coding:utf-8 -*-
import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class Student(Base):
    __tablename__ = 'students'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String(20))
    kana = sqlalchemy.Column(sqlalchemy.String(40))

def main():
    url = 'mysql+pymysql://root:@localhost/test_db?charset=utf8'

    engine = sqlalchemy.create_engine(url, echo=True)

    #Create a session
    Session = sqlalchemy.orm.sessionmaker(bind=engine)
    session = Session()

    #Delete all data
    session.query(Student).delete()

    #Register multiple data at once
    session.add_all([
        Student(id=1, name='Yu Ishizaka', kana='Yu Ishizaka'),
        Student(id=2, name='Seiichi Sugino', kana='Sugi no Seiichi'),
        Student(id=3, name='Yuko Kuwata', kana='Yuko Kuwata'),
        Student(id=4, name='Ai Kurihara', kana='Kurihara Ai'),
        ])

    # id==Update 2 data
    student = session.query(Student).filter(Student.id==2).first()
    student.name = 'Hitoshi Sakuma'
    student.kana = 'Sakuma Jin'

    #Output all data in the table
    print_all_students(session)

    #Confirm data
    session.commit()

#A function that outputs all the data in the table
def print_all_students(session):
    students = session.query(Student).all()
    for student in students:
        print('%d, %s %s' % (student.id, student.name, student.kana))

if __name__ == '__main__':
    main()

Summary

There is nothing special about Update. Suffice it to say that there is no update method, just to operate the object obtained from Session directly.

I may not have bothered to write an article, but I wrote about Delete and Alter, so I'll leave it as a bonus.

How to delete with SQLAlchemy? How to Alter with SQLAlchemy?

Recommended Posts

How to update with SQLAlchemy?
How to Alter with SQLAlchemy?
How to Delete with SQLAlchemy?
How to INNER JOIN with SQLAlchemy
How to get parent id with sqlalchemy
How to update easy_install
How to use SQLAlchemy / Connect with aiomysql
[TF] How to specify variables to update with Optimizer
How to update Python Tkinter to 8.6
Introduction to RDB with sqlalchemy Ⅰ
How to cast with Theano
How to separate strings with','
How to RDP with Fedora31
How to convert a class object to a dictionary with SQLAlchemy
How to get more than 1000 data with SQLAlchemy + MySQLdb
How to cancel RT with tweepy
How to handle session in SQLAlchemy
Python: How to use async with
How to update Spyder in Anaconda
How to use virtualenv with PowerShell
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS
How to deal with imbalanced data
Introduction to RDB with sqlalchemy II
How to get started with Scrapy
How to get started with Python
How to deal with DistributionNotFound errors
How to get started with Django
How to Data Augmentation with PyTorch
How to use FTP with Python
How to calculate date with python
How to install mysql-connector with pip3
How to install Anaconda with pyenv
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to do Bulk Update with PyMySQL and notes [Python]
How to write to update Datastore to async with Google Apps Engine
How to update FC2 blog etc. using XMLRPC with python
How to do arithmetic with Django template
[Blender] How to set shape_key with script
How to title multiple figures with matplotlib
How to add a package with PyCharm
How to update to Chainer 2.0 (Windows + CUDA 8.0 + CUDNN)
How to update Google Sheets from Python
How to install DLIB with 2020 / CUDA enabled
How to use ManyToManyField with Django's Admin
How to use OpenVPN with Ubuntu 18.04.3 LTS
How to use Cmder with PyCharm (Windows)
How to manually update the AMP cache
How to prevent package updates with apt
How to work with BigQuery in Python
How to update php on Amazon linux 2
How to deal with enum compatibility errors
How to use Japanese with NLTK plot
How to do portmanteau test with python
How to search Google Drive with Google Colaboratory
How to display python Japanese with lolipop
How to download youtube videos with youtube-dl
How to use jupyter notebook with ABCI
How to power off Linux with Ultra96-V2
How to update security on CentOS Linux 8