首页 > 代码库 > Python 综合应用小项目一

Python 综合应用小项目一

数据库报错重连机制

利用异常捕获来获取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 = passwd10         self.db_name = db_name11         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.cursor21         except mysql.OperationalError:22             print reconnect db23             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 综合应用小项目一