http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
>>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite:///:memory:', echo=True)
>>> from sqlalchemy.ext.declarative import declarative_base >>> Base = declarative_base()
>>> from sqlalchemy import Column, Integer, String >>> class User(Base): ... _tablename_ = 'users' # this is required at minimum! ... ... 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)
>>> Base.metadata.create_all(engine)
>>> ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') >>> ed_user.name 'ed' >>> ed_user.password 'edspassword' >>> str(ed_user.id) # This won't have an id yet. 'None'
>>> from sqlalchemy.orm import sessionmaker >>> Session = sessionmaker(bind=engine)
>>> session = Session() # Things will not happen until commit or query.
>>> ed_user = User(name='ed', fullname='Ed Jones', password='edspassword') >>> session.add(ed_user) # Now the instance is pending, until a flush.
>>> our_user = session.query(User).filter_by(name='ed').first() >>> our_user <User(name='ed', fullname='Ed Jones', password='edspassword')>
>>> 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')])
>>> ed_user.password = 'f8s7ccs'
>>> session.dirty IdentitySet([<User(name='ed', fullname='Ed Jones', password='f8s7ccs')>])
>>> session.new # doctest: +SKIP 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')>])
>>> session.commit()
>>> ed_user.id # doctest: +NORMALIZE_WHITESPACE 1
URL: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#module-sqlalchemy.dialects.postgresql.psycopg2 Connect String:
postgresql+psycopg2://user:password@host:port/dbname[?key=val&key=val...]
Connection Thru Unix Domain:
create_engine("postgresql+psycopg2://user:pass@/dbname")