django mysql 2006,Django - OperationalError :( 2006,'MySQL服务器已经消失')

Bottom line first: How do you refresh the MySQL connection in django?

Following a MySQL server has gone away error I found that MySQL documentation and other sources (here) suggest increasing the wait_timeout MySQL parameter. To me this seems like a workaround rather than a solution. I'd rather keep a reasonable wait_timeout and refresh the connection in the code.

The error:

File "C:\my_proj\db_conduit.py", line 147, in load_some_model

SomeModel.objects.update()

File "C:\Python26\lib\site-packages\django-1.3-py2.6.egg\django\db\models\manager.py", line 177, in update

return self.get_query_set().update(*args, **kwargs)

File "C:\Python26\lib\site-packages\django-1.3-py2.6.egg\django\db\models\query.py", line 469, in update

transaction.commit(using=self.db)

File "C:\Python26\lib\site-packages\django-1.3-py2.6.egg\django\db\transaction.py", line 142, in commit

connection.commit()

File "C:\Python26\lib\site-packages\django-1.3-py2.6.egg\django\db\backends\__init__.py", line 201, in commit

self._commit()

File "C:\Python26\lib\site-packages\django-1.3-py2.6.egg\django\db\backends\__init__.py", line 46, in _commit

return self.connection.commit()

OperationalError: (2006, 'MySQL server has gone away')

Setup: Django 1.3.0 , MySQL 5.5.14 , innodb 1.1.8 , Python 2.6.6, Win7 64bit

解决方案

having the same issue.

I need idea how to check connection state for MySQLdb connection in django.

i guess it can be achieved by

try:

cursor.execute(sql)

catch OperationalError:

reconnect

is anybody have a better idea?

UPDATE

my decision

self.connection.stat()

if self.connection.errno()!=0:

check state of mysqldb connection if error recreate connection

UPDATE AGAIN

you also need to serve case if connection is close

if self.connection.open:

self.connection.stat()

refresh connection is just recreating it

db_settings = settings.DATABASES['mysql_db']

try:

self.connection = MySQLdb.connect(host=db_settings['HOST'],port=int(db_settings['PORT']),db=db_settings['NAME'],user=db_settings['USER'],passwd=db_settings['PASSWORD'])

except MySQLdb.OperationalError, e:

self.connection = None

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值