torndb 是一个基于 MySQLdb 封装的轻量级模块。

进一步了解请阅读源码:GitHub 源码地址

使用

安装

$ pip install torndb

连接

torndb.Connection(host, database, user=None, password=None, max_idle_time=25200, connect_timeout=0, time_zone=’+0:00’, charset=’utf8’, sql_mode=’TRADITIONAL’, **kwargs)

默认的字符集为 utf8,默认时区为 time_zone='+0:00',默认连接数据库的端口为 3306,如果非 3306 端口则将端口加在 host 后面。

In [1]: import torndb
In [2]: db = torndb.Connection('127.0.0.1:3808', 'test', user='root', password='123123')

数据库操作

torndb 对数据库增删查改的使用较 MySQLdb 要简洁些,把 commit、cursor 都隐藏了,查询返回的结果直接处理成字典,可直接通过字典的形式获取数据库表中对应字段内容。

select 操作常用方法:

  • get:返回一条查询结果,如有多条结果返回则抛出异常
  • query:返回多条查询结果

insert、update、delete 操作一般都习惯使用 execute 方法,当然也可以使用其他方法:insert、insertmany、update、updatemany、delete。

In [1]: import torndb
In [2]: db = torndb.Connection('127.0.0.1:3808', 'test', user='root', password='123123')
 
# 建表
In [3]: sql = 'create table userinfo(id int auto_increment, username varchar(30), email varchar(75), primary key (id))'
In [4]: db.execute(sql)
Out[4]: 0L
 
# 插入数据
In [5]: sql = 'insert into userinfo(username, email) values(%s,%s)'
In [6]: db.execute(sql, 'abner.zhao', 'opsanberzhao@163.com')
Out[6]: 1L
 
In [7]: db.execute(sql, 'mike.zhang', 'mikezhang@gmail.com')
Out[7]: 2L
 
# 查询多条记录
In [8]: sql = 'select username,email from userinfo'
In [9]: db.query(sql)
Out[9]:
[{'email': u'opsanberzhao@163.com', 'username': u'abner.zhao'},
{'email': u'mikezhang@gmail.com', 'username': u'mike.zhang'}]
 
# 查询单条记录
In [10]: sql = 'select email from userinfo where username=%s'
In [11]: db.get(sql,'abner.zhao')
Out[11]: {'email': u'opsanberzhao@163.com'}
 
# 更新
In [12]: sql = 'update userinfo set username="mike.zhao" where id=%s'
In [13]: db.execute(sql, 2)
Out[13]: 0L
 
# 删除
In [14]: sql = 'delete from userinfo where id=%s'
In [15]: db.execute(sql, 2)
Out[15]: 0L

小结

在使用 MySQLdb 过程中,有时会出现2006,'MySQL server has gone away',torndb 能很好的解决该问题。

torndb 每次获取 cursor 的时候会检查链接是否存在或链接的 idle_time 是否超过了 max_idle_time,超过了则会重新建立一个新的链接。而 MySQLdb 的获取 cursor 时却不会重新建立链接。不过 MySQLdb 提供了ping 方法来检查。

总的来说, torndb 使用体验比 MySQLdb 好。

python3使用torndb 需要修改源码参考这个链接https://www.jianshu.com/p/7c72681007c7

参考