sqlalchemy

import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm

#Créer une base de données en mémoire avec sqlite
#engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)

#sqlite
#engine = sqlalchemy.create_engine('sqlite:///:test_sqlite2.db', echo=True)

#mysql
engine = sqlalchemy.create_engine('mysql+pymysql://root:@localhost/test_mysql_database2')

Base = sqlalchemy.ext.declarative.declarative_base()

class Person(Base):
    __tablename__ = 'persons'
    id = sqlalchemy.Column(
        sqlalchemy.Integer, primary_key=True, autoincrement=True)
    name = sqlalchemy.Column(
        sqlalchemy.String(14)
    )


Base.metadata.create_all(engine)

Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()

p1 = Person(name='Mike')
session.add(p1)
p2 = Person(name='Nancy')
session.add(p2)
p3 = Person(name='Jun')
session.add(p3)
session.commit()

p4 = session.query(Person).filter_by(name='Mike').first()
p4.name = 'michel'
session.add(p4)
session.commit()

p5 = session.query(Person).filter_by(name='Nancy').first()
session.delete(p5)
session.commit()

persons = session.query(Person).all()
for person in persons:
    print(person.id, person.name)

production:

1 michel
3 Jun
4 michel
6 Jun

Recommended Posts

sqlalchemy
didacticiel sqlalchemy
Mémo SQLAlchemy
Pièges de SQL Alchemy
SQLAlchemy BaseModel
[SQL Alchemy] Lire les données
Utilisez SQL Alchemy et le multitraitement
Utilisation de base de SQL Alchemy
Utiliser Enum avec SQLAlchemy
Conseils de définition de table sqlalchemy
OperationalError dans SQLAlchemy + SQLite3