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
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
289 | 사진첩에 사진이 추가 되었습니다. | 한승석 | 2003.01.31 | 2076 |
288 | 욕심이 없다. | 한승석 | 2003.01.31 | 2088 |
287 | 서울 대학교 | 한승석 | 2003.01.31 | 2283 |
286 | Re: 신경외과로 변겨ㅣㅇ | 한승석 | 2003.01.31 | 2069 |
285 | 이번 달은 한라병원 응급실에 근무 | 한승석 | 2003.01.31 | 2830 |
284 | 한라 병원 인근의 겜방 ^^ | 한승석 | 2003.01.31 | 2100 |
283 | 한라병원에 도착했습니다... | 한승석 | 2003.01.31 | 2073 |
282 | 홈페이지 새단장 완료 | 한승석 | 2003.01.30 | 2085 |
281 | 도전과 응전 | 한승석 | 2003.01.30 | 2012 |
280 | 요즘 얼굴에 주름이 생겨서 고민.. | 한승석 | 2003.01.30 | 2081 |
279 | 다시 제주도로.. | 한승석 | 2003.01.30 | 2109 |
278 | 자료실에 성소재림 , catch me if you can 등의 영화가 올렸습니다. | 한승석 | 2003.01.29 | 2083 |
277 | 멋진 걸! | 채영광 | 2003.01.29 | 2097 |
276 | 오늘은 인턴 페어웰을 암센터에서~~ | 한승석 | 2003.01.29 | 2095 |
275 | 홈페이지 배경음악을 넣었습니다. | 한승석 | 2003.01.27 | 2102 |
https://stackoverflow.com/questions/207981/how-to-enable-mysql-client-auto-re-connect-with-mysqldb