异常处理
import traceback
import pymysql
def op_mysql(sql,many_tag=False):
try:
conn = pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
db='jxz',port=3306,charset='utf8',
autocommit=True)
except Exception as e:
print('连接出错了~')
else:
cur = conn.cursor(pymysql.cursors.DictCursor)
try:
cur.execute(sql)
except Exception as e:
print(traceback.format_exc())
print('sql语句出错了!')
else:
if many_tag:
result = cur.fetchall() # [{"id":1,"name":"xxx"},{"id":2,"name":"xxx"}]
else:
result = cur.fetchone()
return result
finally:
cur.close()
conn.close()
def conn_mysql():
conn = pymysql.connect(host='118.24.3.40', user='jxz', password='123456',
db='jxz', port=3306, charset='utf8',
autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor)
return conn,cur
def execute_sql(cur,sql):
cur.execute(sql)
return cur.fetchone()
def execute_sql2(cur,sql):
cur.execute(sql)
return cur.fetchall()
def close_mysql(conn,cur):
cur.close()
conn.close()
class MySQL:
def __init__(self):
self.conn = pymysql.connect(host='118.24.3.40', user='jxz', password='123456',
db='jxz', port=3306, charset='utf8',
autocommit=True)
self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
def __del__(self):
self.cur.close()
self.conn.close()
print('连接已经被关闭了')
def execute_one(self,sql):
self.cur.execute(sql)
return self.cur.fetchone()
def execute_many(self,sql):
self.cur.execute(sql)
return self.cur.fetchall()
m = MySQL()
m.execute_one('show tables;')
import traceback a = [1,2,3] # print(a[5]) d = {"a":1} try: print(d['key']) # 1/0 a[5] except Exception as e: print(traceback.format_exc()) print("出异常了!!") else: print('没有出错的情况下') finally: print('什么时候走这里呢')#不管出错或者没出错都走这里