(2018-05-28.Python從Zero到One)8、(Tornado)數(shù)據(jù)庫__1.5.1數(shù)據(jù)庫

5.1 數(shù)據(jù)庫

與Django框架相比,Tornado沒有自帶ORM,對于數(shù)據(jù)庫需要自己去適配。我們使用MySQL數(shù)據(jù)庫。

在Tornado3.0版本以前提供tornado.database模塊用來操作MySQL數(shù)據(jù)庫,而從3.0版本開始,此模塊就被獨立出來,作為torndb包單獨提供。torndb只是對MySQLdb的簡單封裝,不支持Python 3。

torndb安裝

pip install torndb

連接初始化

我們需要在應(yīng)用啟動時創(chuàng)建一個數(shù)據(jù)庫連接實例,供各個RequestHandler使用。我們可以在構(gòu)造Application的時候創(chuàng)建一個數(shù)據(jù)庫實例并作為其屬性,而RequestHandler可以通過self.application獲取其屬性,進而操作數(shù)據(jù)庫實例。

import torndb

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "statics"),
            debug=True,
        )
        super(Application, self).__init__(handlers, **settings)
        # 創(chuàng)建一個全局mysql連接實例供handler使用
        self.db = torndb.Connection(
            host="127.0.0.1",
            database="itcast",
            user="root",
            password="mysql"
        )

使用數(shù)據(jù)庫

新建數(shù)據(jù)庫與表:

create database `itcast` default character set utf8;

use itcast;

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='房屋信息表';

1. 執(zhí)行語句

  • execute(query, parameters, *kwparameters) 返回影響的最后一條自增字段值
  • execute_rowcount(query, parameters, *kwparameters) 返回影響的行數(shù)
    query為要執(zhí)行的sql語句,parameters與kwparameters為要綁定的參數(shù),如:
db.execute("insert into houses(title, position, price, score, comments) values(%s, %s, %s, %s, %s)", "獨立裝修小別墅", "緊鄰文津街", 280, 5, 128)
或
db.execute("insert into houses(title, position, price, score, comments) values(%(title)s, %(position)s, %(price)s, %(score)s, %(comments)s)", title="獨立裝修小別墅", position="緊鄰文津街", price=280, score=5, comments=128)

執(zhí)行語句主要用來執(zhí)行非查詢語句。

class InsertHandler(RequestHandler):
    def post(self):
        title = self.get_argument("title")
        position = self.get_argument("position")
        price = self.get_argument("price")
        score = self.get_argument("score")
        comments = self.get_argument("comments")
        try:
            ret = self.application.db.execute("insert into houses(title, position, price, score, comments) values(%s, %s, %s, %s, %s)", title, position, price, score, comments)
        except Exception as e:
            self.write("DB error:%s" % e)
        else:
            self.write("OK %d" % ret)

2. 查詢語句

  • get(query, parameters, *kwparameters) 返回單行結(jié)果或None,若出現(xiàn)多行則報錯。返回值為torndb.Row類型,是一個類字典的對象,即同時支持字典的關(guān)鍵字索引和對象的屬相訪問。
  • query(query, parameters, *kwparameters) 返回多行結(jié)果,torndb.Row的列表。
    以上一章節(jié)模板中的案例來演示,先修改一下index.html模板,將
<span class="house-title">{{title_join(house["titles"])}}</span>

改為

<span class="house-title">{{house["title"]}}</span>

添加兩個新的handler:

class GetHandler(RequestHandler):
    def get(self):
        """訪問方式為http://127.0.0.1/get?id=111"""
        hid = self.get_argument("id")
        try:
            ret = self.application.db.get("select title,position,price,score,comments from houses where id=%s", hid)
        except Exception as e:
            self.write("DB error:%s" % e)
        else:
            print type(ret)
            print ret
            print ret.title
            print ret['title']
            self.render("index.html", houses=[ret])


class QueryHandler(RequestHandler):
    def get(self):
        """訪問方式為http://127.0.0.1/query"""
        try:
            ret = self.application.db.query("select title,position,price,score,comments from houses limit 10")
        except Exception as e:
            self.write("DB error:%s" % e)
        else:
            self.render("index.html", houses=ret)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容