Skip to content

Instantly share code, notes, and snippets.

@taise
Created June 11, 2015 23:02
Show Gist options
  • Select an option

  • Save taise/e05f373ec020c61d71de to your computer and use it in GitHub Desktop.

Select an option

Save taise/e05f373ec020c61d71de to your computer and use it in GitHub Desktop.
sqlalchemyのサンプル
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
db = {
'driver': 'mysql+mysqldb',
'user': 'root',
'password': '',
'host': 'localhost',
'database': 'sample_data',
'opt': '?charset=utf8'
}
conn_uri = '{driver}://{user}:{password}@{host}/{database}{opt}'.format(**db)
engine = create_engine(conn_uri, echo=True, pool_recycle=3600)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = Session()
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, Sequence
Base = declarative_base()
class Iris(Base):
__tablename__ = 'iris'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
sepal_length = Column(Float)
sepal_width = Column(Float)
petal_length = Column(Float)
petal_width = Column(Float)
species = Column(String(20))
def __repr__(self):
return "<Iris(id='%s', sepal_length='%s', sepal_width='%s'," \
"petal_length='%s'. petal_width='%s', species='%s')>" % (
self.id, self.sepal_length, self.sepal_width,
self.petal_length, self.petal_width, self.species)
iris = Iris()
print(iris)
iris = session.query(Iris).filter_by(species='セトナ').first()
print(iris)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment