tornado连接mysql

Tornado参考链接:http://demo.pythoner.com/itt2zh/index.html

环境:centos 6.7, tornado 4.4.2,python 3.5.1

1、 MySQLdb

Python 2.x 上连接MySQL的库比较多,其中比较著名就是MySQLdb, 大名鼎鼎的Django项目都使用它。地址见:

http://sourceforge.net/projects/mysql-python/,在该网站上有这么一段话:


说明MySQLdb不支持python3.x, 所以我们不能使用它。


2、MySQL Connector

MySQL官方提供的MySQL连接器,已经支持Python3.x的版本了。

具体配置用法参考官网:http://dev.mysql.com/doc/connector-python/en/index.html


3、oursql

支持python3.x,没用过。参考链接:http://packages.python.org/oursql/


4、myconnpy

支持python3.x,没用过。参考链接:https://launchpad.net/myconnpy


5、PyMySQL

支持python3.x,我使用的方法。参考链接:https://github.com/petehunt/PyMySQL/

                                                                                http://www.cnblogs.com/W-Kr/p/5456810.html


6、Torndb

torndb是一个轻量级的基于MySQLdb封装的一个模块,其是tornado框架的一部分。其项目主页为:https://github.com/bdarnell/torndb 。从tornado3.0版本以后,其已经作为一个独立模块发行了。可以通过easy_install 或pip的方式直接安装。


7、ORM框架 SQLAlchemy

SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作。

参考链接:http://www.sqlalchemy.org/

                  http://www.cnblogs.com/pycode/p/mysql-orm.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
在使用`tornado_mysql`的连接池时,可以使用以下代码来执行事务: ```python import tornado.ioloop import tornado.web import tornado.gen import tornado_mysql class MainHandler(tornado.web.RequestHandler): async def get(self): db = self.application.db async with db.pool.acquire() as conn: async with conn.cursor() as cur: try: await cur.execute("START TRANSACTION") await cur.execute("INSERT INTO table_name (column1, column2) VALUES (%s, %s)", (value1, value2)) await cur.execute("UPDATE table_name SET column3 = %s WHERE id = %s", (value3, id)) await cur.execute("COMMIT") self.write("Transaction completed successfully!") except: await cur.execute("ROLLBACK") self.write("Transaction failed") class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), ] self.db = tornado_mysql.Pool( dict(host='localhost', port=3306, user='root', passwd='password', db='database_name'), max_size=10, autocommit=True ) super(Application, self).__init__(handlers) if __name__ == "__main__": app = Application() app.listen(8888) tornado.ioloop.IOLoop.current().start() ``` 在上述代码中,我们首先创建了一个`Pool`对象,它包含了数据库的连接参数和连接池的最大连接数。然后,在我们的请求处理程序中,我们通过`pool.acquire()`方法获取一个连接。我们使用`async with`来确保在完成事务后自动释放该连接。 在使用的连接上创建一个`cursor`来执行事务中的SQL语句。在使用`try/except`块执行SQL语句时,如果任何一个语句失败,我们将立即回滚整个事务。如果所有语句都成功执行,则提交事务。 总之,使用`tornado_mysql`的连接池和事务非常简单,只需要在您的代码中添加一些额外的异步语句即可。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yongche_shi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值