Created
March 3, 2017 09:47
-
-
Save DmitryBe/805fb35e3472b8985c654c8dfb8aa127 to your computer and use it in GitHub Desktop.
SQLAlchemy quick start
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://bytefish.de/blog/first_steps_with_sqlalchemy/ | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy import create_engine | |
from datetime import datetime, timedelta | |
from sqlalchemy import Table, Column, Integer, String, DateTime, ForeignKey | |
from sqlalchemy.orm import relationship, backref | |
from sqlalchemy.orm import sessionmaker | |
Base = declarative_base() | |
class Tag(Base): | |
__tablename__ = 'tags' | |
id = Column(Integer, primary_key=True) | |
name = Column(String(255), unique=True, nullable=False) | |
def __repr__(self): | |
return "<Tag (name='%s')>" % (self.name) | |
# connection | |
engine = create_engine('postgresql://postgres:mysecretpassword@localhost:5432/db01') | |
# create metadata | |
Base.metadata.create_all(engine) | |
# create session | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
# insert data | |
tag_cool = Tag(name='cool') | |
tag_car = Tag(name='car') | |
tag_animal = Tag(name='animal') | |
session.add_all([tag_animal, tag_car, tag_cool]) | |
session.commit() | |
# query data | |
t1 = session.query(Tag).filter(Tag.name == 'cool').first() | |
# update entity | |
t1.name = 'cool-up' | |
session.commit() | |
# delete | |
session.delete(t1) | |
session.commit() |
Really helpful quickstart. Thank you for your service, it is really appreciated
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @DmitryBe
Thank you so much for this incredibly useful quick-start file because the SQLAlchemy docs are detailed but also overwhelming!
Happy Coding,
Michael