SQLAlchemy+MySQL入门
日期:2015年10月14日, 作者:雨水, 优快云博客:
http://blog.youkuaiyun.com/gobitan
SQLAlchemy简介
SQLAlchemy是什么?官方的答案为:The Python SQL Toolkit and Object Relational Mapper。就是Python的SQL工具集和对象关系映射器,类似Java的Hibernate,MyBatis等。它包括两个主要的模块:SQL表达式语言(通常被称为Core)和ORM。
安装SQLAlchemy
$ sudo pip install SQLAlchemy
如果没有报错,可以通过下面检查是否安装成功
>>> import sqlalchemy
>>> sqlalchemy.__version__
'1.0.8'
'1.0.8'
>>>
创建测试数据库testdb
mysql>create database testdb;
mysql> create table products(id int(11) not null auto_increment, name varchar(50) not null, count int(11) not null default '0', primary key (id) );
添加测试数据
mysql> insert products(name, count) values('WuLiangye', 20);
Query OK, 1 row affected (0.01 sec)
mysql> insert products(name, count) values('Maotai', 30);
Query OK, 1 row affected (0.01 sec)
mysql> insert products(name, count) values('Maotai', 30);
Query OK, 1 row affected (0.01 sec)
mysql> select * from products;
+----+-----------+-------+
| id | name | count |
+----+-----------+-------+
| 1 | WuLiangye | 20 |
| 2 | Maotai | 30 |
+----+-----------+-------+
+----+-----------+-------+
| id | name | count |
+----+-----------+-------+
| 1 | WuLiangye | 20 |
| 2 | Maotai | 30 |
+----+-----------+-------+
2 rows in set (0.00 sec)
mysql>
编写SQLAlchemy访问MySQL的程序
将如下代码保存为sql.py
#!/usr/bin/python
from sqlalchemy import create_engine, text, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, Sequence('id'), primary_key=True)
name = Column(String)
count = Column(Integer)
def __repr__(self):
return "<Product(id='%d', name='%s', count='%d')>"%(self.id, self.name, self.count)
DB_CON_STR = 'mysql+mysqldb://root:123456@localhost/testdb?charset=utf8'
engine = create_engine(DB_CON_STR, echo=False) #True will turn on the logging
Session = sessionmaker(bind=engine)
session = Session()
#eg1 via class
#res = session.query(Product).filter(Product.id==1).one()
res = session.query(Product).filter(text("id=1")).one()
print res.id, res.name, res.count
#eg2 via sql
sql = text("select * from products")
res = session.execute(sql).fetchall()
for row in res:
for col in row:
print col,
print
session.close()
程序解释:
(1) create_engine用于创建Engine实例,相当于数据库实例,执行数据库连接操作;
(2) text用来组织字符串的SQL语句;
(3) SQLAlchemy为了便于管理数据库表的映射类,引入Declarative的概念。通过declarative_base获取基类Base,所有的类都必须继承它。
(4) __tablename__关联到数据库的表products
(5) sessionmaker创建会话对象,Session()得到一个会话实例,然后分别以SQL语句和类的方式为例进行了查询。另外,filter的那两行代码是等价的。
程序执行
dennis@ubuntu14:~$ python sql.py
1 WuLiangye 20
1 WuLiangye 20
2 Maotai 30
1 WuLiangye 20
1 WuLiangye 20
2 Maotai 30
dennis@ubuntu14:~$
备注:本来这篇文章的testdb里的products表里也是price列,而不是count,但调试的时候发现sqlalchemy无法导入Decimal,这个问题我将在后面解决它,这里暂时换成Integer类型。2015.10.16注:SQLAlchemy里的对应的Decimal是Numeric,导入它就可以了。
参考资料: