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
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
184 | swap memory | WHRIA | 2019.03.14 | 59 |
183 | sqlite to mysql | WHRIA | 2016.10.18 | 57 |
182 | lvm 축소 확장 [4] | WHRIA | 2020.01.13 | 57 |
181 | php 세션 로그인 | WHRIA | 2020.04.24 | 57 |
180 | bay trail ubuntu 20.04 [1] | WHRIA | 2020.12.24 | 57 |
179 | DD-WRT 펌웨어로 버팔로 G450H 를 업그레이드 | WHRIA | 2015.11.22 | 56 |
178 | 이사 감사 3년 변경등기 | WHRIA | 2015.12.02 | 56 |
177 | 증시의 허풍 예언들 | WHRIA | 2015.11.20 | 55 |
176 | 이율초재 | WHRIA | 2014.10.20 | 54 |
175 | 멀티캐스트 | WHRIA | 2015.11.03 | 53 |
174 | startup | WHRIA | 2020.05.08 | 53 |
173 | WOL shutdown | WHRIA | 2016.01.22 | 52 |
172 | psexec | WHRIA | 2016.07.28 | 52 |
171 | center % crop | WHRIA | 2018.12.27 | 52 |
170 | 싸이월드도 없어지는구나 | WHRIA | 2015.10.10 | 51 |
https://stackoverflow.com/questions/207981/how-to-enable-mysql-client-auto-re-connect-with-mysqldb