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. 如何创建一个基于 .NET Core 3 的 WPF 项目

    在 Connect(); 2018 大会上,微软发布了 .NET Core 3 Preview,以及基于 .NET Core 3 的 WPF:同时还发布了 Visual Studio 2019 预览版 ...

  2. enjoy dollar vs cash dollar

    當 enJoy 卡 客 戶 憑 enJoy 卡 於 enJoy 卡 「 特 約 商 戶 」 簽 賬 消 費 , 累 積 之 enJoy Dollars 及 Cash Dollars 可 在 同 一 交 ...

  3. 【转】每天一个linux命令(42):kill命令

    原文网址:http://www.cnblogs.com/peida/archive/2012/12/20/2825837.html Linux中的kill命令用来终止指定的进程(terminate a ...

  4. 微信JS-SDK官方示例程序

    示例地址:http://203.195.235.76/jssdk/ /* * 注意: * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能 ...

  5. linux 信号处理 一 (基本概念)

    信号是Linux编程中非常重要的部分,本文将详细介绍信号机制的基本概念.Linux对信号机制的大致实现方法.如何使用信号,以及有关信号的几个系统调用. 信号机制是进程之间相互传递消息的一种方法,信号全 ...

  6. ALGO-6_蓝桥杯_算法训练_安慰奶牛

    记: 本题目考的是最小生成数,可使用Kruskal算法 第一次,20分 原因:使用动态数组,有概率报运行错误(大雾= =) 第二次,100分 原因:改用静态数组,一次过 示例代码: #include ...

  7. 【Spring环境搭建】在Myeclipse下搭建Spring环境-web开发

    <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" ...

  8. Zabbix监控windows的CPU利用率和其他资源

    zabbix的WEB端--配置-模板--Template OS Windows--项目--创建项目 名称:UserPerfCountercpu 键值:UserPerfCountercpu 数据类型:数 ...

  9. bzoj1066 蜥蜴

    Description 在一个r行c列的网格地图中有一些高度不同的石柱,一些石柱上站着一些蜥蜴,你的任务是让尽量多的蜥蜴逃到边界外. 每行每列中相邻石柱的距离为1,蜥蜴的跳跃距离是d,即蜥蜴可以跳到平 ...

  10. [转]预编译 ASP.NET 网站

    转自:如何:预编译 ASP.NET 网站 Visual Studio 2005   预编译 ASP.NET 网站可缩短用户的初始响应时间,因为页在第一次被请求时无需编译.这对于经常更新的大型网站尤其有 ...