In [1]:
import sqlalchemy
sqlalchemy.__version__
Out[1]:
In [2]:
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
In [3]:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
In [4]:
from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
In [5]:
User.__table__
Out[5]:
In [6]:
Base.metadata.create_all(engine)
In [7]:
ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
In [8]:
ed_user.name
Out[8]:
In [9]:
ed_user.password
Out[9]:
In [10]:
str(ed_user.id)
Out[10]:
In [11]:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
In [12]:
session = Session()
In [13]:
session.add(ed_user)
In [14]:
our_user = session.query(User).filter_by(name='ed').first()
In [15]:
our_user
#<User(name='ed', fullname='Ed Jones', password='edspassword')>
Out[15]:
In [16]:
ed_user is our_user
#True
Out[16]:
In [17]:
session.add_all([
User(name='wendy', fullname='Wendy Williams', password='foobar'),
User(name='mary', fullname='Mary Contrary', password='xxg527'),
User(name='fred', fullname='Fred Flinstone', password='blah')])
In [18]:
ed_user.password = 'f8s7ccs'
In [19]:
session.dirty
#IdentitySet([<User(name='ed', fullname='Ed Jones', password='f8s7ccs')>])
Out[19]:
In [20]:
session.new
#IdentitySet([<User(name='wendy', fullname='Wendy Williams', password='foobar')>,
#<User(name='mary', fullname='Mary Contrary', password='xxg527')>,
#<User(name='fred', fullname='Fred Flinstone', password='blah')>])
Out[20]:
In [21]:
session.commit()
In [22]:
ed_user.id
Out[22]: