數據庫
- torndb安裝
- 連接初始化
- 執行語句
- execute
- execute_rowcount
- 查詢語句
- get
- query
與Django框架相比,Tornado沒有自帶ORM,對于數據庫需要自己去適配。我們使用MySQL數據庫。
在Tornado3.0版本以前提供tornado.database模塊用來操作MySQL數據庫,而從3.0版本開始,此模塊就被獨立出來,作為torndb包單獨提供。torndb只是對MySQLdb的簡單封裝,不支持Python 3。
1.torndb安裝
pip install torndb
2.連接初始化
我們需要在應用啟動時創建一個數據庫連接實例,供各個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")
?
使用數據庫
新建數據庫與表:
#
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='房屋信息表';
?