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. HDU 4681 string 求最长公共子序列的简单DP+暴力枚举

    先预处理,用求最长公共子序列的DP顺着处理一遍,再逆着处理一遍. 再预处理串a和b中包含串c的子序列,当然,为了使这子序列尽可能短,会以c 串的第一个字符开始 ,c 串的最后一个字符结束 将这些起始位 ...

  2. HTML第一课——基础知识普及【2】

    关注公众号:自动化测试实战 img标签 我们先看一下文档结构: 这里我们文件当前位置就是lesson.html,所以现在我们img属性src给的值要进入imgs文件夹,所以我们可以用相对路径来表示,看 ...

  3. HDU3584 Cube

    分析 三维树状数组,跟二维的差不多,只不过容斥的不一样. 更新区间\((x_1,y_1,z_1)\rightarrow(x_2,y_2,z_2)\)时,需要利用容斥原理.须要更新的节点更新如下: \[ ...

  4. LeetCode Pascal's Triangle && Pascal's Triangle II Python

    Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given ...

  5. BAT编程

    echo 表示显示此命令后的字符  echo off 表示在此语句后所有运行的命令都不显示命令行本身  @与echo off相象,但它是加在每个命令行的最前面,表示运行时不显示这一行的命令行(只能影响 ...

  6. Sql语句导出数据库表结构及查询表视图储存过程名

    --一句Sql把表结构全部查询出来 SELECT 表名 = Case When A.colorder=1 Then D.name Else '' End, 表说明 = Case When A.colo ...

  7. Maven的dependency type属性

    官方地址: http://maven.apache.org/ref/3.5.2/maven-model/maven.html (搜索:Some examples are jar, war, ejb-c ...

  8. POJ2559最大矩形面积——单调栈

    题目:http://poj.org/problem?id=2559 #include<iostream> #include<cstdio> using namespace st ...

  9. arcgis license manager 10.2服务无法启动

    (步骤)1. 用cmd切换到 license manager 安装目录,如 C:\Program Files (x86)\ArcGIS\License10.2\bin,输入: Lmgrd -z -c ...

  10. iview-admin打包笔记

    在程序根目录右键打开cmd,输入 npm run build 这时就会进入打包的步骤,打包好之后就会在程序根目录出现一个dist的文件夹,里面有一个index.html文件和另一个dist的文件夹. ...