Introduction to Python's ORM framework SQLAlchemy tutorial

  • 2020-04-02 13:39:35
  • OfStack


The concept of SQLAlchemy is that the magnitude and performance of the SQL database is more important than the collection of objects. The abstraction of a collection of objects is more important than tables and rows.

A installed SQLAlchemy

pip install sqlalchemy

The installation succeeds if the import does not report an error
>>> import sqlalchemy
>>> sqlalchemy.__version__
'0.9.1'
>>>

Use sqlalchemy for database operations

1. Define meta information bound to the engine


(env)ghost@ghost-H61M-S2V-B3:~/project/flask/fsql$ python
Python 2.7.3 (default, Apr 10 2013, 05:13:16) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///. / sqlalchemy. Db ', echo = True) & have spent # define the engine
>>> metadata = MetaData(engine) #  Binding element information 
>>>

2. Create the table and initialize the database


>>> users_table = Table('users', metadata,
...     Column('id', Integer, primary_key=True),
...     Column('name', String(40)),
...     Column('email', String(120)))
>>> 
>>> users_table.create()
2014-01-09 10:03:32,436 INFO sqlalchemy.engine.base.Engine 
CREATE TABLE users (
    id INTEGER NOT NULL, 
    name VARCHAR(40), 
    email VARCHAR(120), 
    PRIMARY KEY (id)
)

                                                 
2014-01-09 10:03:32,436 INFO sqlalchemy.engine.base.Engine ()
2014-01-09 10:03:32,575 INFO sqlalchemy.engine.base.Engine COMMIT
>>>

After executing the above code, we will create a users table with three fields: id, name and email


(env)ghost@ghost-H61M-S2V-B3:~/project/flask/fsql$ sqlite3 sqlalchemy.db 
SQLite version 3.7.13 2012-06-11 02:05:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
users
sqlite>

3. Basic operation, insert

If the table already exists, you don't want to create on the second run,   Use the autoload Settings


>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///./sqlalchemy.db', echo=True)
>>> metadata = MetaData(engine)
>>> users_table = Table('users', metadata, autoload=True)
2014-01-09 10:20:01,580 INFO sqlalchemy.engine.base.Engine PRAGMA table_info("users")
2014-01-09 10:20:01,581 INFO sqlalchemy.engine.base.Engine ()
2014-01-09 10:20:01,582 INFO sqlalchemy.engine.base.Engine PRAGMA foreign_key_list("users")
2014-01-09 10:20:01,583 INFO sqlalchemy.engine.base.Engine ()
2014-01-09 10:20:01,583 INFO sqlalchemy.engine.base.Engine PRAGMA index_list("users")
2014-01-09 10:20:01,583 INFO sqlalchemy.engine.base.Engine ()
>>> users_table
Table('users', MetaData(bind=Engine(sqlite:///./sqlalchemy.db)), Column('id', INTEGER(), table=<users>, primary_key=True, nullable=False), Column('name', VARCHAR(length=40), table=<users>), Column('email', VARCHAR(length=120), table=<users>), schema=None)
>>>

Instantiate an insert handle


>>> i = users_table.insert()
>>> i
<sqlalchemy.sql.dml.Insert object at 0x31bc850>
>>> print i
INSERT INTO users (id, name, email) VALUES (?, ?, ?)
>>> i.execute(name='rsj217', email='rsj21@gmail.com')
2014-01-09 10:24:02,250 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, email) VALUES (?, ?)
2014-01-09 10:24:02,250 INFO sqlalchemy.engine.base.Engine ('rsj217', 'rsj21@gmail.com')
2014-01-09 10:24:02,251 INFO sqlalchemy.engine.base.Engine COMMIT
<sqlalchemy.engine.result.ResultProxy object at 0x31bce10>
>>> i.execute({'name': 'ghost'},{'name': 'test'})
2014-01-09 10:24:57,537 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name) VALUES (?)
2014-01-09 10:24:57,537 INFO sqlalchemy.engine.base.Engine (('ghost',), ('test',))
2014-01-09 10:24:57,537 INFO sqlalchemy.engine.base.Engine COMMIT
<sqlalchemy.engine.result.ResultProxy object at 0x31bcd50>
>>>

The database content is


sqlite> select * from users;
1|rsj217|rsj21@gmail.com
2|ghost|
3|test|
sqlite>

Query deletes and inserts alike require an instance of an sqlalchemy.sql.dml object

Three using ORM

Using orm simply maps the python class to the table of the database, eliminating the need to write SQL statements directly

Create a mapping


>>> class User(object):
...     def __repr__(self):
...             return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.email)
... 
>>> mapper(User, users_table)  #  Create a mapping 
<Mapper at 0x31bcfd0; User> 
>>> ul = User()
>>> ul.name
>>> print ul
User(None, None)
>>> print ul.name
None
>>>

Establish a session


The query


>>> session = create_session()
>>> session
<sqlalchemy.orm.session.Session object at 0x31bef10>
>>> query = session.query(User)
>>> query
<sqlalchemy.orm.query.Query object at 0x31bee50>
>>> u = query.filter_by(name='rsj217').first()
2014-01-09 10:44:23,809 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.email AS users_email 
FROM users 
WHERE users.name = ?
 LIMIT ? OFFSET ?
2014-01-09 10:44:23,809 INFO sqlalchemy.engine.base.Engine ('rsj217', 1, 0)
>>> u.name
u'rsj217'
>>>

insert


>>> from sqlalchemy import *
>>> from sqlalchemy.orm import *
>>> engine = create_engine('sqlite:///./sqlalchemy.db')
>>> metadata = MetaData(engine)
>>> users_table = Table('users', metadata, autoload=True)
>>> class User(object): pass
... 
>>> mapper(User, users_table)
<Mapper at 0x18185d0; User>
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> u = User()
>>> u.name = 'new'
>>> session.add(u)
>>> session.flush()
>>> session.commit()
>>>

Note how the session is set up. Different versions of sqlalchemy have a better sessionmaker approach

The rest of the advanced operations such as deleting relational things refer to the official documentation.


Related articles: