5 数据库

知识点

  • torndb安装
  • 连接初始化
  • 执行语句
    • execute
    • execute_rowcount
  • 查询语句
    • get
    • query

5.1 数据库

与Django框架相比,Tornado没有自带ORM,对于数据库需要自己去适配。我们使用MySQL数据库。

在Tornado3.0版本以前提供tornado.database模块用来操作MySQL数据库,而从3.0版本开始,此模块就被独立出来,作为torndb包单独提供。torndb只是对MySQLdb的简单封装,不支持Python 3。

torndb安装

pip install torndb

连接初始化

我们需要在应用启动时创建一个数据库连接实例,供各个RequestHandler使用。我们可以在构造Application的时候创建一个数据库实例并作为其属性,而RequestHandler可以通过self.application获取其属性,进而操作数据库实例。

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)
# 创建一个全局mysql连接实例供handler使用
self.db = torndb.Connection(
host="127.0.0.1",
database="itcast",
user="root",
password="mysql"
)

使用数据库

新建数据库与表:

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. 执行语句

  • execute(query, parameters, *kwparameters) 返回影响的最后一条自增字段值
  • execute_rowcount(query, parameters, *kwparameters) 返回影响的行数

query为要执行的sql语句,parameters与kwparameters为要绑定的参数,如:

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)

执行语句主要用来执行非查询语句。

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) 返回单行结果或None,若出现多行则报错。返回值为torndb.Row类型,是一个类字典的对象,即同时支持字典的关键字索引和对象的属相访问。
  • query(query, parameters, *kwparameters) 返回多行结果,torndb.Row的列表。

以上一章节模板中的案例来演示,先修改一下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)

5.2 练习

  1. 复习MySQL的使用与sql语法。

  2. 练习在Tornado中使用torndb操作数据库。

Tornado之链接数据库的更多相关文章

  1. PHP学习-链接数据库

    链接数据库文件:conn.php <?php $conn = mysql_connect("localhost:3306","root","us ...

  2. PHP 链接数据库1(连接数据库&简单的登录注册)

    对 解析变量的理解 数据库的名称和表的名称不能重复 从结果中取出的数据   都是以数组的形式取出的 1.PHP查询数据库中的某条信息 //PHP链接数据库 /*1.造链接对象 IP地址 用户名 密码 ...

  3. JDBC的使用(一):引用外部jar;代码链接数据库

    一:引用外部jar 1.首先不jar文件放到项目下: 2.在Eclipse中,右键相应的项目--构建路径--配置构建路径--库--添加外部jar:选中-打开-应用-确定. 二:代码链接数据库 1.加载 ...

  4. Connect to Database Using Custom params链接数据库配置参数说明

    使用RF的关键字Connect to Database Using Custom params链接数据库,对应的参数说明: a)     第一个参数我使用的是cx_Oracle,就写这个 b)     ...

  5. php链接数据库

      1:找到 ySQL服务器 $conn = mysql_connect("localhost","","") or die("链 ...

  6. 安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误

    安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误 这个错误几个月以前解决过一次,但是到又碰到的时候,竟然完全忘记当时怎么解决的了, 看来上了年纪记忆真是越来越不行了... 解决方案很简单 ...

  7. jsp链接数据库

    数据库表代码: /*Navicat MySQL Data Transfer Source Server : localhost_3306Source Server Version : 50528Sou ...

  8. 本地开发 localhost链接数据库比127.0.0.1慢

    自己手写一段代码的时候发现一个问题  链接数据库的时候 用 127.0.0.1比localhost明显的快,localhost要等一下才会有响应 而127.0.0.1就是瞬间响应.一番排查,发现了一个 ...

  9. 2017-3-2 C#链接数据库实现登陆

    只是链接一个数据库就有好多的知识:) 实际操作下来,主要是两种登陆方式: 1.Windows的身份验证: 2.Sql Sever的身份验证: 两种的方法不同,但是主要是通过复制创建数据库的字符串来链接 ...

随机推荐

  1. JQuery 基本知识,选择器,事件,DOM操作

    一.基本知识 Jquery是什么? 它就是一套JS方法包,jQuery是一个快速,小巧,功能丰富的JavaScript库.它使得HTML文档遍历和操作,事件处理,动画和Ajax更容易使用易于使用的AP ...

  2. spring boot sso 学习资源

    diy: 关键字: springboot sso:public boolean preHandle(HttpServletRequest request, HttpServletResponse re ...

  3. 【vue】Mac上安装Node和NPM

    http://bubkoo.com/2017/01/08/quick-tip-multiple-versions-node-nvm/ 作为前端开发者,node和npm安装必不可少.然而有时会因为安装新 ...

  4. log4net保存到数据库系列五、新增数据库字段

    园子里面有很多关于log4net保存到数据库的帖子,但是要动手操作还是比较不易,从头开始学习log4net数据库日志一.WebConfig中配置log4net 一.WebConfig中配置log4ne ...

  5. FastAdmin 开发环境详细设置

    一图胜千言 FastAdmin开发环境 Windows 网页安装 鼠标点点就可以了,不用说明. 命令行安装 环境准备 装有 Windows 7 的PC .(这是一句废话,不用理这句.) 服务器软件 A ...

  6. Windows nginx php cgi-fcgi 配置 xdebug

    之前使用的是 Apache + PHP,不用怎么配置就可以. 由于服务器用的是 nginx,为了和服务器一致,所以本地开发也改为 nginx. 开始只是简单的开启 xdebug, 发现并不行. 找了一 ...

  7. bzoj 4650(洛谷 1117) [Noi2016]优秀的拆分——枚举长度的关键点+后缀数组

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4650 https://www.luogu.org/problemnew/show/P1117 ...

  8. POJ3468——树状数组支持两个区间操作

    题目:http://poj.org/problem?id=3468 推断过程可自己查,得式子:fixsum(x) = (x+1) * ∑(i=1,x)fi - ∑(i=1,x)i*fi; 其中 f 是 ...

  9. 【linux】Linux软连接和硬链接

    1.Linux链接概念 Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link).默认情况下,ln命令产生硬链接. [硬连接] 硬连接指通过索引 ...

  10. 【python】实例-用户登录系统

    有N,E,Q三个选择,若选择Q或者中断,则系统退出.若其他选项,则持续让用户选择. #!/usr/bin/env python db = {} def newuser(): prompt = 'log ...