5.1 数据库

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

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

torndb安装

python2 : pip install torndb    python3:pip install torndb_for_python3

连接初始化

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

import torndb_for_python3 as  torndb
from tornado.web import RequestHandler,Application class Application(Application):
'''重写应用,增加数据库连接功能'''
def __init__(self,handlers,**kwargs):
super(Application,self).__init__(handlers=handlers,**kwargs)
print(kwargs)
self.db = torndb.Connection(
host='192.168.135.29',
database='test',
user='admin',
password='Wyf@1314'
)

使用数据库

新建数据库与表:

create database `test` default character set utf8;

use test;

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)

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

insert 语句一般如果表结构有id字段会返回这个自增的唯一ID字段

class UseTorndbHandler(RequestHandler):def post(self, *args, **kwargs):
'''测试上传数据报保存到数据库'''
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的列表。

以上一章节模板中的案例来演示,先修改一下 subblock_for_usedb_index.html 模板,将

<span class="house-title">{{title_join(house["titles"])}}</span>

改为

<span class="house-title">{{house["title"]}}</span>
Handler 测试: get、query查询测试代码Handler如下GET get()方法处理, 写入在POST  post()方法处理
class UseTorndbHandler(RequestHandler):
def get(self, *args, **kwargs):
'''测试从数据库获取数据做数量展示'''
limit = self.get_query_argument('query_limit',default='10')
house_id = self.get_query_argument('houseid',default=None)
if house_id:
try:
ret = self.application.db.get("select title,position,price,score,comments from houses where id=%s", house_id)
except Exception as e:
self.write("DB Error : %s" % e)
else:
print('ret type: ', type(ret))
print(ret)
print(ret.title)
print(ret['title'])
self.render('subblock_for_usedb_index_one_house.html', **ret,title_join=house_title_join)
else:
try:
sql = "select title,position,price,score,comments from houses limit %s" % limit
ret = self.application.db.query( sql)
except Exception as e:
self.write("DB Error : %s" % e)
else:
print('ret type: ',type(ret) )
print(ret)
# print(ret.title)
# print(ret['title'])
self.render('subblock_for_usedb_index.html', houses=ret,title_join=house_title_join)
def post(self, *args, **kwargs):
'''测试上传数据报保存到数据库'''
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)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一个house测试</title>
</head>
<body>
<li class="house-item">
<a href=""><img src="/static/images/home01.jpg"></a>
<div class="house-desc">
<div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div>
<div class="house-price">¥<span>{{price}}</span>/晚</div>
<div class="house-intro">
<span class="house-title">{{title}}</span>
<em>整套出租 - {{score}}分/{{comments}}点评 - {{position}}</em>
</div>
</div>
</li>
</body>
</html>

subblock_for_usedb_index_one_house.html

{% extends "base.html" %}

{% block page_title %}
<title>数据库,多个house模板index</title>
{% end %} {% block css_files %}
<link href="{{static_url('css/index.css')}}" rel="stylesheet">
{% end %} {% block js_files %}
<script src="{{static_url('js/index.js')}}"></script>
{% end %} {% block header %}
<div class="nav-bar">
<h3 class="page-title">房 源</h3>
</div>
{% end %} {% block body %}
<ul class="house-list">
{% if len(houses) > 0 %}
{% for house in houses %}
<li class="house-item">
<a href=""><img src="/static/images/home01.jpg"></a>
<div class="house-desc">
<div class="landlord-pic"><img src="/static/images/landlord01.jpg"></div>
<div class="house-price">¥<span>{{house["price"]}}</span>/晚</div>
<div class="house-intro">
<span class="house-title">{{ house["title"]}}</span>
<em>整套出租 - {{house["score"]}}分/{{house["comments"]}}点评 - {{house["position"]}}</em>
</div>
</div>
</li>
{% end %}
{% else %}
对不起,暂时没有房源。
{% end %}
</ul>
{% end %} {% block footer %}
<p><span><i class="fa fa-copyright"></i></span>爱家租房&nbsp;&nbsp;享受家的温馨</p>
{% end %}

subblock_for_usedb_index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
{% block page_title %}{% end %}
<link href="{{static_url('plugins/bootstrap/css/bootstrap.min.css')}}" rel="stylesheet">
<link href="{{static_url('plugins/font-awesome/css/font-awesome.min.css')}}" rel="stylesheet">
<link href="{{static_url('css/reset.css')}}" rel="stylesheet">
<link href="{{static_url('css/main.css')}}" rel="stylesheet">
{% block css_files %}{% end %}
</head>
<body>
<div class="container">
<div class="top-bar">
{% block header %}{% end %}
</div>
{% block body %}{% end %}
<div class="footer">
{% block footer %}{% end %}
</div>
</div> <script src="{{static_url('js/jquery.min.js')}}"></script>
<script src="{{static_url('plugins/bootstrap/js/bootstrap.min.js')}}"></script>
{% block js_files %}{% end %}
</body>
</html>

base.html



Tornado WEB服务器框架 Epoll-- 【Mysql数据库】的更多相关文章

  1. Tornado WEB服务器框架 Epoll

    引言: 回想Django的部署方式 以Django为代表的python web应用部署时采用wsgi协议与服务器对接(被服务器托管),而这类服务器通常都是基于多线程的,也就是说每一个网络请求服务器都会 ...

  2. Tornado WEB服务器框架 Epoll-- 【模板】

    4.2 使用模板 1. 路径与渲染 使用模板,需要仿照静态文件路径设置一样,向web.Application类的构造函数传递一个名为template_path的参数来告诉Tornado从文件系统的一个 ...

  3. jdbc连接阿里云服务器上的MySQL数据库 及 数据库IP限制

    问题1:Jdbc 如何连接阿里云服务器上的MySQL数据库? 解决: 上截图: 其中IP是阿里云服务器的公网IP地址. 问题2:   刚开始接手开发的时候,使用Navicat连接阿里云服务器上的数据后 ...

  4. 服务器怎么安装mysql数据库

    有些小伙伴们想自己玩玩服务器.可以买了服务以后,发现服务器就是一个大框子,没有数据存储.啥都没有,这时候就需要各种软件操作来逐步安装这些东西, 一.使用的工具:xshell(从官网上下载),目的是得使 ...

  5. 使用Navicat连接阿里云服务器上的MySQL数据库=======Linux 开放 /etc/hosts.allow

    使用Navicat连接阿里云服务器上的MySQL数据库   1.首先打开Navicat,文件>新建连接> 2,两张连接方法 1>常规中输入数据库的主机名,端口,用户名,密码 这种直接 ...

  6. Windows(Server)环境安装Web服务器(Apache,PHP,Mysql)图文教程

    Windows下Apache+PHP+MySQL搭建web服务器的方法,windows Server Install Apache PHP MySQL(图文详解) 环境准备: Windows Serv ...

  7. 使用Navicat连接阿里云服务器中的Mysql数据库

    1.首先将阿里云服务器中的安全组添加上Mysql的端口3306,如下图所示: 步骤就是进入到阿里云的官网,点击右上角控制台,在左边选择云服务器ECS--->实例 点击图中的管理按钮,然后选择本实 ...

  8. 使用Navicat远程连接阿里云ECS服务器上的MySQL数据库

    一.必须给服务器的安全组规则设置端口放行规则,在管理控制台中设置: 之后填写配置,授权对象是授权的IP,其中0.0.0.0/0为所有IP授权,之后保存; 二.Navicat使用的配置 在编辑连接处,要 ...

  9. 基于gin的golang web开发:访问mysql数据库

    web开发基本都离不开访问数据库,在Gin中使用mysql数据库需要依赖mysql的驱动.直接使用驱动提供的API就要写很多样板代码.你可以找到很多扩展包这里介绍的是jmoiron/sqlx.另外还有 ...

随机推荐

  1. Collections集合工具类的常用方法

    Collections集合工具类的方法 addAll与shuffle import java.util.ArrayList; import java.util.Collections; /* - ja ...

  2. vue3 学习笔记(九)——script setup 语法糖用了才知道有多爽

    刚开始使用 script setup 语法糖的时候,编辑器会提示这是一个实验属性,要使用的话,需要固定 vue 版本. 在 6 月底,该提案被正式定稿,在 v3.1.3 的版本上,继续使用但仍会有实验 ...

  3. 查找 Search

    如果值域小一点. 那么我们有一个很精妙的做法. 分块完维护数字\(cnt\),和一个\(bitset\)信息. 然而小不得. 那么我们考虑维护后缀\(nxt_i\),表示第\(i\)位后,最近的\(a ...

  4. MYSQL5.8----M3

    333333333333333333333333333 mysql> DESC user; +----------+---------------------+------+-----+---- ...

  5. 选择省份、选择省市区举例【c#】【js】

    <style type="text/css"> .labelhide { -webkit-box-shadow: 0px 1px 0px 0px #f3f3f3 !im ...

  6. 学习java 7.8

    学习内容: 被static修饰的不需要创建对象,直接用类名引用即可 内部类访问特点:内部类可以直接访问外部类的成员,包括私有 外部类访问内部类的成员,必须创建对象 成员内部类,内部类为私有,Outer ...

  7. Scala(六)【模式匹配】

    目录 一.基本语法 二.匹配固定值 三.守卫 四.匹配类型 五.匹配集合 1.Array 2.List 3.元祖 4.对象和样例类 六.偏函数 七.赋值匹配 八.for循环匹配 一.基本语法 在匹配某 ...

  8. 大数据学习day14-----第三阶段-----scala02------1. 元组 2.类、对象、继承、特质 3.函数(必须掌握)

    1. 元组 映射是K/V对偶的集合,对偶是元组的最简单的形式,元组可以装着多个不同类型的值 1.1 特点 元组相当于一个特殊的数组,其长度和内容都可变,并且数组中可以装任何类型的数据,其主要用处就是存 ...

  9. 【Penetration】红日靶场(一)

    nmap探查存活主机 nmap -sP 10.10.2.0/24 图片: https://uploader.shimo.im/f/cfuQ653BEvyA42FR.png!thumbnail?acce ...

  10. [学习总结]3、Android---Scroller类(左右滑动效果常用的类)

    参考资料:http://blog.csdn.net/vipzjyno1/article/details/24592591 非常感谢这个兄弟! 在android学习中,动作交互是软件中重要的一部分,其中 ...