0% found this document useful (0 votes)
482 views10 pages

Python Database Handling with SQLAlchemy

This document introduces SQLAlchemy, an ORM (object-relational mapper) that allows Python code to interact with SQL databases. It shows how SQLAlchemy can be used at a low level to define tables and columns, at a higher level with an ORM to define classes that map to tables, and how relationships between classes can be defined and queried. Key benefits of SQLAlchemy mentioned are faster development, cleaner code, protection from SQL injection, and an active community.

Uploaded by

sxurdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
482 views10 pages

Python Database Handling with SQLAlchemy

This document introduces SQLAlchemy, an ORM (object-relational mapper) that allows Python code to interact with SQL databases. It shows how SQLAlchemy can be used at a low level to define tables and columns, at a higher level with an ORM to define classes that map to tables, and how relationships between classes can be defined and queried. Key benefits of SQLAlchemy mentioned are faster development, cleaner code, protection from SQL injection, and an active community.

Uploaded by

sxurdc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
  • Introduction to SQLAlchemy: Introduces SQLAlchemy and highlights its advantages over using SQL directly, emphasizing code cleanliness and reduced risk of SQL injection.
  • Plain DBAPI + SQL: Demonstrates standard database operations using the DBAPI with SQL, including table creation and data insertion examples.
  • SQLAlchemy (low-level): Explains the low-level usage of SQLAlchemy for metadata and table management without requiring ORM features.
  • SQLAlchemy (ORM): Covers using SQLAlchemy's ORM feature, detailing class-based table definitions and object relational mapping capabilities.
  • SQLAlchemy (ORM) Continued: Continues discussion on ORM, focusing on session management and object querying in SQLAlchemy.
  • Relationships in SQLAlchemy: Introduces relationship handling in SQLAlchemy, showing how to define and manage relationships between tables using foreign keys.
  • Relationships in SQLAlchemy Continued: Further explores relationships in SQLAlchemy with examples of querying and modifying relational data.
  • Relationships in SQLAlchemy - Advanced Queries: Shows advanced relationship queries in SQLAlchemy, focusing on using relationships to fetch associated data.
  • Additional SQLAlchemy Features: Briefly lists various advanced features of SQLAlchemy such as query options, custom types, and signals.
  • Benefits of SQLAlchemy: Summarizes the advantages of using SQLAlchemy, including quicker development, clean code, and a supportive community.

Write Python instead of SQL!

An introduction to
SQLAlchemy.
Plain DBAPI+SQL
>>> import psycopg2
>>> conn = psycopg2.connect('dbname=test')
>>> cur = conn.cursor()
>>> cur.execute("CREATE TABLE test (id serial PRIMARY KEY, data varchar)")
>>> cur.execute("INSERT INTO test VALUES (%s)", ("Little Bobby 'tables'",))
>>> cur.execute("INSERT INTO test VALUES ('%s')" % ("Little Bobby 'tables'",))
ProgrammingError: syntax error at or near "tables"
LINE 1: INSERT INTO test (data) VALUES ('Little Bobby 'tables'')
SQLAlchemy (low-level)
>>> from sqlalchemy import *
>>> metadata = MetaData()
>>> table = Table('test', metadata,
Column('id', Integer, primary_key=True),
Column('name', String))
>>> engine = create_engine('postgresql:///test')
>>> metadata.create_all(engine)
>>> conn = engine.connect()
>>> table.insert(bind=engine).values(name="Little Bobby 'tables'").execute()
>>> conn.execute(select([table])).fetchone()
(1, u"Little Bobby 'tables'")
SQLAlchemy (ORM)
>>> from sqlalchemy import *
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarative_base()
>>> class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
def __repr__(self):
return '<User({}, {})>'.format(self.id, self.name)
>>> engine = create_engine('postgresql:///test')
>>> Base.metadata.create_all(engine)
SQLAlchemy (ORM)
>>> from sqlalchemy.orm import sessionmaker
>>> session = sessionmaker(bind=engine)()

>>> user = User(name='Bobby Tables')


>>> session.add(user)
>>> session.commit()

>>> session.query(User).one()
<User(1, Bobby Tables)>

>>> user.name = "DROP ALL THE 'TABLES!"


>>> session.query(User).one()
<User(1, DROP ALL THE 'TABLES!)>
>>> session.rollback()
Let’s have a relationship
>>> class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(String)
def __repr__(self):
return '<Group({}, {})>'.format(self.id, self.name)

>>> class User(Base):


# ...
group_id = Column(Integer, ForeignKey('groups.id'), index=True)
group = relationship('Group', lazy=False, backref='users')
def __repr__(self):
return '<User({}, {}, {})>'.format(self.id, self.group, self.name)
Let’s have a relationship
>>> u = User(name='Bobby Tables')
>>> u2 = User(name='Vimmy McVimface')
>>> g = Group(name='Scriptkiddies')
>>> session.add_all([u, u2, g])
>>> session.commit()

>>> u
<User(1, None, Bobby Tables)>
>>> u2
<User(2, None, Vimmy McVimface)>
>>> g
<Group(1, Scriptkiddies)>
Let’s have a relationship
>>> u.group = g
>>> g.users
[<User(1, <Group(1, Scriptkiddies)>, Bobby Tables)>]

>>> g.users.append(u2)
>>> u2
<User(2, <Group(1, Scriptkiddies)>, Vimmy McVimface)>
>>> g.users
[<User(1, <Group(1, Scriptkiddies)>, Bobby Tables)>,
<User(2, <Group(1, Scriptkiddies)>, Vimmy McVimface)>]
What else is there
Query options to control column/relationship loading
Cascading along relationships
Custom types
Signals
Why use SQLAlchemy again?
Sacrifice a little bit of performance / SQL purity for
much faster development
Cleaner / shorter code
Basically no SQL injection risks
Excellent documentation http://docs.sqlalchemy.org/en/rel_1_0/
Very helpful community (#sqlalchemy on freenode)

Write Python instead of SQL!
An introduction to 
SQLAlchemy.
Plain DBAPI+SQL
>>> import psycopg2
>>> conn = psycopg2.connect('dbname=test')
>>> cur = conn.cursor()
>>> cur.execute("CREAT
SQLAlchemy (low-level)
>>> from sqlalchemy import *
>>> metadata = MetaData()
>>> table = Table('test', metadata,
Column('id'
SQLAlchemy (ORM)
>>> from sqlalchemy import *
>>> from sqlalchemy.ext.declarative import declarative_base
>>> Base = declarat
SQLAlchemy (ORM)
>>> from sqlalchemy.orm import sessionmaker
>>> session = sessionmaker(bind=engine)()
>>> user = User(name='
Let’s have a relationship
>>> class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Colum
Let’s have a relationship
>>> u = User(name='Bobby Tables')
>>> u2 = User(name='Vimmy McVimface')
>>> g = Group(name='Scriptk
Let’s have a relationship
>>> u.group = g
>>> g.users
[<User(1, <Group(1, Scriptkiddies)>, Bobby Tables)>]
>>> g.users.append
What else is there
Query options to control column/relationship loading
Cascading along relationships
Custom types
Signals
Why use SQLAlchemy again?
Sacrifice a little bit of performance / SQL purity for 
much faster development
Cleaner / shorter c

You might also like