SQLAlchemy基本操作和常用技巧
时间:2021-07-01 10:21:17
帮助过:12人阅读
- apt-get install mysql-server
- apt-get install mysql-client
- apt-get install libmysqlclient15-dev
[python] view plain
copy
- apt-get install python-mysqldb
[python] view plain
copy
- easy_install MySQL-Python
[python] view plain
copy
- easy_install SQLAlchemy
操作系统,遇到问题就 Google 一下吧。我是在 Mac OS X 上开发的,途中也遇到些问题,不过当时没记下来……
值得一提的是我用了 MySQL-Python 来连 MySQL,因为不支持异步调用,所以和 Tornado 不是很搭。不过性能其实很好,因此以后再去研究下其他方案吧……
import create_engine
- from sqlalchemy.orm import sessionmaker
-
- DB_CONNECT_STRING = ‘mysql+mysqldb://root:123@localhost/ooxx?charset=utf8‘
- engine = create_engine(DB_CONNECT_STRING, echo=True)
- DB_Session = sessionmaker(bind=engine)
- session = DB_Session()
- def initialize(self):
- self.session = models.DB_Session()
-
-
- def on_finish(self):
- self.session.close()
拿到 session 后,就可以执行 SQL 了:
[python] view plain copy
- session.execute(‘create database abc‘)
- print session.execute(‘show databases‘).fetchall()
- session.execute(‘use abc‘)
- print session.execute(‘select * from user where id = 1‘).first()
- print session.execute(‘select * from user where id = :id‘, {‘id‘: 1}).first()
于是来定义一个表:
[python] view plain copy
- from sqlalchemy import Column
- from sqlalchemy.types import CHAR, Integer, String
- from sqlalchemy.ext.declarative import declarative_base
-
- BaseModel = declarative_base()
-
- def init_db():
- BaseModel.metadata.create_all(engine)
-
- def drop_db():
- BaseModel.metadata.drop_all(engine)
-
-
- class User(BaseModel):
- __tablename__ = ‘user‘
-
- id = Column(Integer, primary_key=True)
- name = Column(CHAR(30))
-
- init_db()
接着就开始使用这个表吧:
[python] view plain copy
- from sqlalchemy import func, or_, not_
-
- user = User(name=‘a‘)
- session.add(user)
- user = User(name=‘b‘)
- session.add(user)
- user = User(name=‘a‘)
- session.add(user)
- user = User()
- session.add(user)
- session.commit()
-
- query = session.query(User)
- print query
- print query.statement
- for user in query:
- print user.name
- print query.all()
- print query.first().name
- print query.filter(User.id == 2).first().name
- print query.get(2).name
- print query.filter(‘id = 2‘).first().name
-
- query2 = session.query(User.name)
- print query2.all()
- print query2.limit(1).all()
- print query2.offset(1).all()
- print query2.order_by(User.name).all()
- print query2.order_by(‘name‘).all()
- print query2.order_by(User.name.desc()).all()
- print query2.order_by(‘name desc‘).all()
- print session.query(User.id).order_by(User.name.desc(), User.id).all()
-
- print query2.filter(User.id == 1).scalar()
- print session.query(‘id‘).select_from(User).filter(‘id = 1‘).scalar()
- print query2.filter(User.id > 1, User.name != ‘a‘).scalar()
- query3 = query2.filter(User.id > 1)
- query3 = query3.filter(User.name != ‘a‘)
- print query3.scalar()
- print query2.filter(or_(User.id == 1, User.id == 2)).all()
- print query2.filter(User.id.in_((1, 2))).all()
-
- query4 = session.query(User.id)
- print query4.filter(User.name == None).scalar()
- print query4.filter(‘name is null‘).scalar()
- print query4.filter(not_(User.name == None)).all()
- print query4.filter(User.name != None).all()
-
- print query4.count()
- print session.query(func.count(‘*‘)).select_from(User).scalar()
- print session.query(func.count(‘1‘)).select_from(User).scalar()
- print session.query(func.count(User.id)).scalar()
- print session.query(func.count(‘*‘)).filter(User.id > 0).scalar()
- print session.query(func.count(‘*‘)).filter(User.name == ‘a‘).limit(1).scalar() == 1
- print session.query(func.sum(User.id)).scalar()
- print session.query(func.now()).scalar()
- print session.query(func.current_timestamp()).scalar()
- print session.query(func.md5(User.name)).filter(User.id == 1).scalar()
-
- query.filter(User.id == 1).update({User.name: ‘c‘})
- user = query.get(1)
- print user.name
-
- user.name = ‘d‘
- session.flush()
- print query.get(1).name
-
- session.delete(user)
- session.flush()
- print query.get(1)
-
- session.rollback()
- print query.get(1).name
- query.filter(User.id == 1).delete()
- session.commit()
- print query.get(1)
下面开始介绍一些进阶的知识。
[python] view plain copy
- session.execute(
- User.__table__.insert(),
- [{‘name‘: `randint(1, 100)`,‘age‘: randint(1, 100)} for i in xrange(10000)]
- )
- session.commit()
如何让执行的
SQL 语句增加前缀?
使用 query 对象的 prefix_with() 方法:
- session.execute(User.__table__.insert().prefix_with(‘IGNORE‘), {‘id‘: 1, ‘name‘: ‘1‘})
1, name=‘ooxx‘)
- session.merge(user)
- session.commit()
-
如何使用无符号整数?
可以使用 MySQL 的方言:
import INTEGER
- id = Column(INTEGER(unsigned=True), primary_key=True)
-
‘from‘, CHAR(10))
[python] view plain copy
- User.name.property.columns[0].type.length
[python] view plain copy
- class User(BaseModel):
- __table_args__ = {
- ‘mysql_engine‘: ‘InnoDB‘,
- ‘mysql_charset‘: ‘utf8‘
- }
不建议全用 utf8mb4 代替 utf8,因为前者更慢,索引会占用更多空间。
import randint
- from sqlalchemy import ForeignKey
-
- class User(BaseModel):
- __tablename__ = ‘user‘
- id = Column(Integer, primary_key=True)
- age = Column(Integer)
-
- class Friendship(BaseModel):
- __tablename__ = ‘friendship‘
- id = Column(Integer, primary_key=True)
- user_id1 = Column(Integer, ForeignKey(‘user.id‘))
- user_id2 = Column(Integer, ForeignKey(‘user.id‘))
-
- for i in xrange(100):
- session.add(User(age=randint(1, 100)))
- session.flush()
- for i in xrange(100):
- session.add(Friendship(user_id1=randint(1, 100), user_id2=randint(1, 100)))
- session.commit()
- session.query(User).filter(User.age < 50).delete()
- 执行这段代码时,你应该会遇到一个错误:
1451, ‘Cannot delete or update a parent row: a foreign key constraint fails (`ooxx`.`friendship`, CONSTRAINT `friendship_ibfk_1` FOREIGN KEY (`user_id1`) REFERENCES `user` (`id`))‘) ‘DELETE FROM user WHERE user.age < %s‘ (50,) 原因是删除 user 表的数据,可能会导致 friendship 的外键不指向一个真实存在的记录。在默认情况下,MySQL 会拒绝这种操作,也就是 RESTRICT。InnoDB 还允许指定
ON DELETE 为 CASCADE 和 SET NULL,前者会删除 friendship 中无效的记录,后者会将这些记录的外键设为 NULL。
除了删除,还有可能更改主键,这也会导致 friendship 的外键失效。于是相应的就有 ON UPDATE 了。其中 CASCADE 变成了更新相应的外键,而不是删除。
而在 SQLAlchemy 中是这样处理的:
[python] view plain copy
- class Friendship(BaseModel):
- __tablename__ = ‘friendship‘
- id = Column(Integer, primary_key=True)
- user_id1 = Column(Integer, ForeignKey(‘user.id‘, ondelete=‘CASCADE‘, onupdate=‘CASCADE‘))
- user_id2 = Column(Integer, ForeignKey(‘user.id‘, ondelete=‘CASCADE‘, onupdate=‘CASCADE‘))
如何连接表?
[python] view plain copy
- from sqlalchemy import distinct
- from sqlalchemy.orm import aliased
-
- Friend = aliased(User, name=‘Friend‘)
- print session.query(User.id).join(Friendship, User.id == Friendship.user_id1).all()
- print session.query(distinct(User.id)).join(Friendship, User.id == Friendship.user_id1).all()
- print session.query(User.id).join(Friendship, User.id == Friendship.user_id1).distinct().all()
- print session.query(Friendship.user_id2).join(User, User.id == Friendship.user_id1).order_by(Friendship.user_id2).distinct().all()
- print session.query(Friendship.user_id2).select_from(User).join(Friendship, User.id == Friendship.user_id1).order_by(Friendship.user_id2).distinct().all()
- print session.query(User.id, Friendship.user_id2).join(Friendship, User.id == Friendship.user_id1).all()
- print session.query(User.id, Friendship.user_id2).join(Friendship, User.id == Friendship.user_id1).filter(User.id < 10).all()
- print session.query(User.id, Friend.id).join(Friendship, User.id == Friendship.user_id1).join(Friend, Friend.id == Friendship.user_id2).all()
- print session.query(User.id, Friendship.user_id2).outerjoin(Friendship, User.id == Friendship.user_id1).all()
这里我没提到 relationship,虽然它看上去很方便,但需要学习的内容实在太多,还要考虑很多性能上的问题,所以干脆自己 join 吧。
为什么无法删除 in 操作查询出来的记录?
[python] view plain copy
- session.query(User).filter(User.id.in_((1, 2, 3))).delete()
抛出这样的异常:
not evaluate current criteria in Python. Specify ‘fetch‘ or False for the synchronize_session parameter. 但这样是没问题的:
1, User.id == 2, User.id == 3)).delete() 搜了下找到《Sqlalchemy delete subquery》这个问题,提到了 delete 的一个注意点:删除记录时,默认会尝试删除 session 中符合条件的对象,而 in 操作估计还不支持,于是就出错了。解决办法就是删除时不进行同步,然后再让
session 里的所有实体都过期:
[python] view plain copy
- session.query(User).filter(User.id.in_((1, 2, 3))).delete(synchronize_session=False)
- session.commit()
此外,update 操作也有同样的参数,如果后面立刻提交了,那么加上 synchronize_session=False 参数会更快。
- @classmethod
- def get_by_id(cls, session, id, columns=None, lock_mode=None):
- if hasattr(cls, ‘id‘):
- scalar = False
- if columns:
- if isinstance(columns, (tuple, list)):
- query = session.query(*columns)
- else:
- scalar = True
- query = session.query(columns)
- else:
- query = session.query(cls)
- if lock_mode:
- query = query.with_lockmode(lock_mode)
- query = query.filter(cls.id == id)
- if scalar:
- return query.scalar()
- return query.first()
- return None
- BaseModel.get_by_id = get_by_id
- @classmethod
- def get_all(cls, session, columns=None, offset=None, limit=None, order_by=None, lock_mode=None):
- if columns:
- if isinstance(columns, (tuple, list)):
- query = session.query(*columns)
- else:
- query = session.query(columns)
- if isinstance(columns, str):
- query = query.select_from(cls)
- else:
- query = session.query(cls)
- if order_by is not None:
- if isinstance(order_by, (tuple, list)):
- query = query.order_by(*order_by)
- else:
- query = query.order_by(order_by)
- if offset:
- query = query.offset(offset)
- if limit:
- query = query.limit(limit)
- if lock_mode:
- query = query.with_lockmode(lock_mode)
- return query.all()
- BaseModel.get_all = get_all
- @classmethod
- def count_all(cls, session, lock_mode=None):
- query = session.query(func.count(‘*‘)).select_from(cls)
- if lock_mode:
- query = query.with_lockmode(lock_mode)
- return query.scalar()
- BaseModel.count_all = count_all
- @classmethod
- def exist(cls, session, id, lock_mode=None):
-