首页 > 编程语言 > 详细

Python 综合应用小项目一

时间:2017-07-19 19:20:24      阅读:371      评论:0      收藏:0      [点我收藏+]

数据库报错重连机制

利用异常捕获来获取mysql断开的报错,然后再重连

技术分享
 1 import MySQLdb as mysql
 2 
 3 class DB:
 4     def __init__(self,host,user,passwd,db_name):
 5         self.conn = None
 6         self.cursor = None
 7         self.host = host
 8         self.user = user
 9         self.passwd = passwd
10         self.db_name = db_name
11         self.connect()
12     def connect(self):
13         self.conn = mysql.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.db_name)
14         self.conn.autocommit(True)
15         self.cursor = self.conn.cursor()
16 
17     def execute(self,sql):
18         try:
19             self.cursor.execute(sql)
20             return self.cursor
21         except mysql.OperationalError:
22             print ‘reconnect db‘
23             self.connect()
24             return self.execute(sql)
25     def list(self,table_name,col_name=‘*‘):
26         sql = ‘select %s from %s‘%(col_name,table_name)
27         res = self.execute(sql)
28         return res.fetchall() 
29         
30 
31 
32 db = DB(host=‘59.110.12.*‘,user=‘****‘,passwd=‘*****‘,db_name=‘******‘)
View Code

 

Python 综合应用小项目一

原文:http://www.cnblogs.com/nopnog/p/7207297.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!