mysql python reconnect
2020.04.24 23:05
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb.connect()
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
db = DB()
sql = "SELECT * FROM foo"
cur = db.query(sql)
# wait a long time for the Mysql connection to timeout
cur = db.query(sql)
# still works
댓글 2
-
WHRIA
2020.04.24 23:10
-
WHRIA
2020.04.24 23:13
#!/usr/bin/env python import MySQLdb class DisconnectSafeCursor(object): db = None cursor = None def __init__(self, db, cursor): self.db = db self.cursor = cursor def close(self): self.cursor.close() def execute(self, *args, **kwargs): try: return self.cursor.execute(*args, **kwargs) except MySQLdb.OperationalError: self.db.reconnect() self.cursor = self.db.cursor() return self.cursor.execute(*args, **kwargs) def fetchone(self): return self.cursor.fetchone() def fetchall(self): return self.cursor.fetchall() class DisconnectSafeConnection(object): connect_args = None connect_kwargs = None conn = None def __init__(self, *args, **kwargs): self.connect_args = args self.connect_kwargs = kwargs self.reconnect() def reconnect(self): self.conn = MySQLdb.connect(*self.connect_args, **self.connect_kwargs) def cursor(self, *args, **kwargs): cur = self.conn.cursor(*args, **kwargs) return DisconnectSafeCursor(self, cur) def commit(self): self.conn.commit() def rollback(self): self.conn.rollback() disconnectSafeConnect = DisconnectSafeConnection
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
1549 | 아래 주소는 새 홈페이지 주소입니다. | 한승석 | 2002.06.19 | 2120 |
1548 | 여기는 집입니다~ | 한승석 | 2003.01.10 | 2102 |
1547 | 승석이가 피부과에 합격했답니다. | 한승석 | 2003.01.10 | 2318 |
1546 | 외로움 | 한승석 | 2003.01.27 | 2106 |
1545 | 홈페이지 배경음악을 넣었습니다. | 한승석 | 2003.01.27 | 2107 |
1544 | 오늘은 인턴 페어웰을 암센터에서~~ | 한승석 | 2003.01.29 | 2106 |
1543 | 멋진 걸! | 채영광 | 2003.01.29 | 2106 |
1542 | 자료실에 성소재림 , catch me if you can 등의 영화가 올렸습니다. | 한승석 | 2003.01.29 | 2094 |
1541 | 다시 제주도로.. | 한승석 | 2003.01.30 | 2115 |
1540 | 요즘 얼굴에 주름이 생겨서 고민.. | 한승석 | 2003.01.30 | 2094 |
1539 | 도전과 응전 | 한승석 | 2003.01.30 | 2021 |
1538 | 홈페이지 새단장 완료 | 한승석 | 2003.01.30 | 2093 |
1537 | 한라병원에 도착했습니다... | 한승석 | 2003.01.31 | 2090 |
1536 | 한라 병원 인근의 겜방 ^^ | 한승석 | 2003.01.31 | 2113 |
1535 | 이번 달은 한라병원 응급실에 근무 | 한승석 | 2003.01.31 | 2843 |
https://stackoverflow.com/questions/207981/how-to-enable-mysql-client-auto-re-connect-with-mysqldb