使用torndb模块解决mysql断连问题
torndb是facebook开源的一个基于MySQLdb二次封装的一个mysql模块,新封装的这个模块比较小,是一个只有2百多行代码的py文件。虽然代码短,功能确相较MySQLdb简便不少,并且该模块由于增加了reconnect方法和max_idel_time参数,解决了mysql的断连问题。该模块之前在 python torndb模块 篇中也提到过。这里就结合上一篇 python mysql 断连报错处理 问题,比较下使用原生MySQLdb模块和使用torndb模块的代码。
一、代码比较
1、使用MySQLdb模块的代码
1import MySQLdb
2def getTerm(db,tag):
3 cursor = db.cursor()
4 query = "SELECT term_id FROM wp_terms where name=%s "
5 count = cursor.execute(query,tag)
6 rows = cursor.fetchall()
7 db.commit()
8 #db.close()
9 if count:
10 term_id = [int(rows[id][0]) for id in range(count)]
11 return term_id
12 else:return None
13def addTerm(db,tag):
14 cursor = db.cursor()
15 query = "INSERT into wp_terms (name,slug,term_group) values (%s,%s,0)"
16 data = (tag,tag)
17 cursor.execute(query,data)
18 db.commit()
19 term_id = cursor.lastrowid
20 sql = "INSERT into wp_term_taxonomy (term_id,taxonomy,description) values (%s,'post_tag',%s) "
21 value = (term_id,tag)
22 cursor.execute(sql,value)
23 db.commit()
24 db.close()
25 return int(term_id)
26def addCTag(db,data):
27 cursor = db.cursor()
28 query = '''INSERT INTO `wp_term_relationships` (
29 `object_id` ,
30 `term_taxonomy_id`
31 )
32 VALUES (
33 %s, %s) '''
34 cursor.executemany(query,data)
35 db.commit()
36 db.close()
37dbconn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='361way', port=3306, charset='utf8', init_command='set names utf8')
38tags = ['mysql','1111','aaaa','bbbb','ccccc','php','abc','python','java']
39tagids = []
40for tag in tags:
41 if termid:
42 try:
43 dbconn.ping()
44 except:
45 dbconn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='361way', port=3306, charset='utf8', init_command='set names utf8')
46 print tag, 'tag id is ',termid
47 termid = getTerm(dbconn,tag)
48 tagids.extend(termid)
49 else:
50 try:
51 dbconn.ping()
52 except:
53 dbconn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='361way', port=3306, charset='utf8', init_command='set names utf8')
54 termid = addTerm(dbconn,tag)
55 print 'add tag',tag,'id is ' ,termid
56 tagids.append(termid)
57print 'tag id is ',tagids
58postid = '35'
59tagids = list(set(tagids))
60ctagdata = []
61for tagid in tagids:
62 ctagdata.append((postid,tagid))
63try:
64 dbconn.ping()
65except:
66 dbconn = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='361way', port=3306, charset='utf8', init_command='set names utf8')
67 addCTag(dbconn,ctagdata)
2、使用torndb的代码
1#!/usr/bin/python
2#coding=utf-8
3import torndb
4def getTerm(db,tag):
5 query = "SELECT term_id FROM wp_terms where name=%s "
6 rows = db.query(query,tag)
7 termid = []
8 for row in rows:
9 termid.extend(row.values())
10 return termid
11def addTerm(db,tag):
12 query = "INSERT into wp_terms (name,slug,term_group) values (%s,%s,0)"
13 term_id = db.execute_lastrowid(query,tag,tag)
14 sql = "INSERT into wp_term_taxonomy (term_id,taxonomy,description) values (%s,'post_tag',%s) "
15 db.execute(sql,term_id,tag)
16 return term_id
17def addCTag(db,data):
18 query = "INSERT INTO wp_term_relationships (object_id,term_taxonomy_id) VALUES (%s, %s) "
19 db.executemany(query,data)
20dbconn = torndb.Connection('localhost:3306','361way',user='root',password='123456')
21tags = ['mysql','1111','aaaa','bbbb','ccccc','php','abc','python','java']
22tagids = []
23for tag in tags:
24 termid = getTerm(dbconn,tag)
25 if termid:
26 print tag, 'tag id is ',termid
27 tagids.extend(termid)
28 else:
29 termid = addTerm(dbconn,tag)
30 print 'add tag',tag,'id is ' ,termid
31 tagids.append(termid)
32print 'All tags id is ',tagids
33postid = '35'
34tagids = list(set(tagids))
35ctagdata = []
36for tagid in tagids:
37 ctagdata.append((postid,tagid))
38addCTag(dbconn,ctagdata)
从两者的代码上来看,使用torndb模块和原生相比,发现可以省略如下两部分:
1、torndb模块不需要db.cursor进行处理,无不需要db.comment提交,torndb是自动提交的;
2、torndb不需要在每次调用时,进行db.ping()判断数据库socket连接是否断开,因为torndb增加了reconnect方法,支持自动重连。
二、torndb的方法
torndb提供的参数和方法有:
1execute 执行语句不需要返回值的操作。
2execute_lastrowid 执行后获得表id,一般用于插入后获取返回值。
3executemany 可以执行批量插入。返回值为第一次请求的表id。
4executemany_rowcount 批量执行。返回值为第一次请求的表id。
5get 执行后获取一行数据,返回dict。
6iter 执行查询后,返回迭代的字段和数据。
7query 执行后获取多行数据,返回是List。
8close 关闭
9max_idle_time 最大连接时间
10reconnect 关闭后再连接
使用示例:
1mysql> CREATE TABLE `ceshi` (`id` int(1) NULL AUTO_INCREMENT ,`num` int(1) NULL ,PRIMARY KEY (`id`));
2>>> import torndb
3>>> db = torndb.Connection("127.0.0.1","数据库名","用户名", "密码", 24*3600) # 24*3600为超时时间
4>>> get_id1 = db.execute_lastrowid("insert ceshi(num) values('1')")
5>>> print get_id1
61
7>>> args1 = [('2'),('3'),('4')]
8>>> get1 = db.executemany("insert ceshi(num) values(%s)", args1)
9>>> print get1
102
11>>> rows = db.iter("select * from ceshi")
12>>> for i in rows:
13… print i
三、报错
在使用过程中可能遇到的错误:
1File "/home/361way/database.py", line 145, in execute_lastrowid
2 self._execute(cursor, query, parameters)
3 File "/home/361way/database.py", line 207, in _execute
4 return cursor.execute(query, parameters)
5 File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 159, in execute
6 query = query % db.literal(args)
7TypeError: not enough arguments for format string
写上面的代码时,我刚开始还是试着使用MySQLdb模块的方式引用数据,结果发现报参数的错误 ,经查看代码发现 ,torndb在使用几个sql方法时较MySQLdb精简过了。具体各个方法的传参方法如下(注意参数个数):
1close()
2reconnect()
3iter(query, *parameters, **kwparameters)
4query(query, *parameters, **kwparameters)
5get(query, *parameters, **kwparameters)
6execute(query, *parameters, **kwparameters)
7execute_lastrowid(query, *parameters, **kwparameters)
8execute_rowcount(query, *parameters, **kwparameters)
9executemany(query, parameters)
10executemany_lastrowid(query, parameters)
11executemany_rowcount(query, parameters)
12update(query, *parameters, **kwparameters)
13updatemany(query, parameters)
14insert(query, *parameters, **kwparameters)
15insertmany(query, parameters)
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/torndb-resolve-mysql-disconn/4067.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.