与Django框架相比,Tornado没有自带ORM,对于数据库须要本身去适配。咱们使用MySQL数据库。mysql
在Tornado3.0版本之前提供tornado.database模块用来操做MySQL数据库,而从3.0版本开始,此模块就被独立出来,做为torndb包单独提供。torndb只是对MySQLdb的简单封装,不支持Python 3。sql
pip install torndb
咱们须要在应用启动时建立一个数据库链接实例,供各个RequestHandler使用。咱们能够在构造Application的时候建立一个数据库实例并做为其属性,而RequestHandler能够经过self.application获取其属性,进而操做数据库实例。数据库
# 放在application.py 最下面 super(Application, self).__init__(handlers, **settings) # 建立一个全局mysql链接实例供handler使用 self.db = torndb.Connection( host="127.0.0.1", database="igeek", user="root", password="mysql" )
新建数据库与表:app
#
create database igeek default character set utf8; use igeek; create table houses ( id bigint(20) unsigned not null auto_increment comment '房屋编号', title varchar(64) not null default '' comment '标题', position varchar(32) not null default '' comment '位置', price int not null default 0, score int not null default 5, comments int not null default 0, primary key(id) )ENGINE=InnoDB default charset=utf8 comment='房屋信息表';