Tornado-数据库(torndb包)

203 阅读2分钟
1、torndb数据库简介

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



2、torndb安装

pip install torndb



3、连接初始化

class Applicatin(tornado.web.application):

def __init__(self):

handler = [

(r"index/",IndexHandler),

]


settings = dic(

template_path = os.path.join(os.path.dirname(__file__),"templates"),

static_path = os.path.join(os.path.dirname(__file__),"static")

)


super(Application,self).__init__(handler,**settings)


self.db = torndb.Connection(

host = "127,0,0,1",

database = "ihome",

user = "root",

pwd = "mysql"

)



4、使用数据库

1、执行语句

1、execute(query,*patameters,**kwparameters)

1、query:要执行的sql语句


2、*patameters:为sql语句中指定的参数进行数据的传值


3、**kwparameters:为sql语句中指定的参数进行数据的赋值操作


4、返回影响的最后一条自增字段值

2、execute_rowcount(query,(patameters,**kwparameters))

1、query:要执行的sql语句


2、*patameters:为sql语句中指定的参数进行数据的传值


3、**kwparameters:为sql语句中指定的参数进行数据的赋值操作


4、返回受影响行数


3、实例:

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)



2、查询语句

1、get(query, parameters, *kwparameters)

1、query:要执行的sql语句


2、*patameters:为sql语句中指定的参数进行数据的传值


3、**kwparameters:为sql语句中指定的参数进行数据的赋值操作


4、返回单行结果或None,若出现多行则报错。返回值为torndb.Row类型,是一个类字典的对象,即同时支持字典的关键字索引和对象的属相访问。


2、query(query, parameters, *kwparameters)

1、query:要执行的sql语句


2、*patameters:为sql语句中指定的参数进行数据的传值


3、**kwparameters:为sql语句中指定的参数进行数据的赋值操作


4、返回多行结果,torndb.Row的列表。