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