Tornado之链接数据库
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 练习
复习MySQL的使用与sql语法。
练习在Tornado中使用torndb操作数据库。
Tornado之链接数据库的更多相关文章
- PHP学习-链接数据库
链接数据库文件:conn.php <?php $conn = mysql_connect("localhost:3306","root","us ...
- PHP 链接数据库1(连接数据库&简单的登录注册)
对 解析变量的理解 数据库的名称和表的名称不能重复 从结果中取出的数据 都是以数组的形式取出的 1.PHP查询数据库中的某条信息 //PHP链接数据库 /*1.造链接对象 IP地址 用户名 密码 ...
- JDBC的使用(一):引用外部jar;代码链接数据库
一:引用外部jar 1.首先不jar文件放到项目下: 2.在Eclipse中,右键相应的项目--构建路径--配置构建路径--库--添加外部jar:选中-打开-应用-确定. 二:代码链接数据库 1.加载 ...
- Connect to Database Using Custom params链接数据库配置参数说明
使用RF的关键字Connect to Database Using Custom params链接数据库,对应的参数说明: a) 第一个参数我使用的是cx_Oracle,就写这个 b) ...
- php链接数据库
1:找到 ySQL服务器 $conn = mysql_connect("localhost","","") or die("链 ...
- 安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误
安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误 这个错误几个月以前解决过一次,但是到又碰到的时候,竟然完全忘记当时怎么解决的了, 看来上了年纪记忆真是越来越不行了... 解决方案很简单 ...
- jsp链接数据库
数据库表代码: /*Navicat MySQL Data Transfer Source Server : localhost_3306Source Server Version : 50528Sou ...
- 本地开发 localhost链接数据库比127.0.0.1慢
自己手写一段代码的时候发现一个问题 链接数据库的时候 用 127.0.0.1比localhost明显的快,localhost要等一下才会有响应 而127.0.0.1就是瞬间响应.一番排查,发现了一个 ...
- 2017-3-2 C#链接数据库实现登陆
只是链接一个数据库就有好多的知识:) 实际操作下来,主要是两种登陆方式: 1.Windows的身份验证: 2.Sql Sever的身份验证: 两种的方法不同,但是主要是通过复制创建数据库的字符串来链接 ...
随机推荐
- unicode汉字编码
原来我使用的一直是 \u4e00-\u9fa5 ,今天在匹配中文标点的时候匹配不上,就查了一下相关资料,原来unicode跟中文有关的范围还有好几个. 字符范围表 1.标准CJK文字 范围:\u340 ...
- jQuery事件绑定汇总(包括一些无法获取事件的问题)
★ $(document).on('click', 'button[name=closeLayerOut2]', function () { ...... }); $(document).on('cl ...
- 转 微软发布TX(LINQ To Logs And Traces)
作者 Roopesh Shenoy ,译者 马德奎 发布于 一月 09, 2014 | 微软开源技术公司于近日发布了Tx,这是一个开源项目,可以使用日志/跟踪文件辅助调试,以及创建实时监控和告警系统. ...
- Tensoflw.js - 02 - 模型与内存管理(易懂)
Tensoflw.js - 02 - 模型与内存管理(易懂) 参考 W3Cschool 文档:https://www.w3cschool.cn/tensorflowjs/ 本文主要翻译一些英文注释,添 ...
- echarts 知识点
echarts map 禁止放大缩小,设置 calculable 为 false 即可. calculable: false echarts 报错: There is a chart instance ...
- bzoj 4556 [Tjoi2016&Heoi2016]字符串——后缀数组+主席树
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4556 本来只要查 ht[ ] 数组上的前驱和后继就行,但有长度的限制.可以二分答案解决!然后 ...
- 一组十六进制的字符串每两个转成对应值的byte
/// <summary> /// 一组十六进制的字符串每两个转成对应值的byte,比如4142 会成 AB对应的byte列表 /// </summary> /// <p ...
- python中hashlib md5
如下两种方法,结果相同 import hashlib import time m = hashlib.md5() m.update(str(time.time()).encode('utf-8')) ...
- 关于有时候导入maven项目时候报错(有红色叹号,类中导入的包提示"the import java.util cannot be resolve,")
------解决方案--------------------解决方案:右键项目-------buildpath--------最下面那个configura...的选择libraries找到JRE(这个 ...
- python之BeautifulSoup4的例子
仅作演示用 from bs4 import BeautifulSoup import urllib.request webfile = urllib.request.urlopen('http://w ...