torndb 是一个基于 MySQLdb 封装的轻量级模块。python
进一步了解请阅读源码:GitHub 源码地址git
使用
安装
$ 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)github
默认的字符集为 utf8
,默认时区为 time_zone='+0:00'
,默认链接数据库的端口为 3306
,若是非 3306 端口则将端口加在 host 后面。sql
In [
1]: import torndb
In [
2]: db = torndb.Connection('127.0.0.1:3808', 'test', user='root', password='123123')
|
数据库操做
torndb 对数据库增删查改的使用较 MySQLdb 要简洁些,把 commit、cursor 都隐藏了,查询返回的结果直接处理成字典,可直接经过字典的形式获取数据库表中对应字段内容。数据库
select 操做经常使用方法:post
- get:返回一条查询结果,若有多条结果返回则抛出异常
- query:返回多条查询结果
insert、update、delete 操做通常都习惯使用 execute 方法,固然也能够使用其余方法:insert、insertmany、update、updatemany、delete。spa
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 能很好的解决该问题。code
torndb 每次获取 cursor 的时候会检查连接是否存在或连接的 idle_time 是否超过了 max_idle_time,超过了则会从新创建一个新的连接。而 MySQLdb 的获取 cursor 时却不会从新创建连接。不过 MySQLdb 提供了ping 方法来检查。server
总的来讲, torndb 使用体验比 MySQLdb 好。ip
python3使用torndb 须要修改源码参考这个连接https://www.jianshu.com/p/7c72681007c7