mysql auto reconnect_Python mysql (using pymysql) auto reconnect

2023-11-07

I'm not sure if this is possible, but I'm looking for a way to reconnect to mysql database when the connection is lost. All the connections are held in a gevent queue but that shouldn't matter I think. I'm sure if I put some time in, I can come up with a way to reconnect to the database. However I was glancing pymysql code and I saw that there is a 'ping' method in Connection class, which I'm not sure exactly how to use.

The method looks like it will reconnect first time but after that it switched the reconnect flag to False again? Can I use this method, or is there a different way to establish connection if it is lost? Even if it is not pymysql how do people tackle, database servers going down and having to re-establish connection to mysql server?

def ping(self, reconnect=True):

''' Check if the server is alive '''

if self.socket is None:

if reconnect:

self._connect()

reconnect = False

else:

raise Error("Already closed")

try:

self._execute_command(COM_PING, "")

return self._read_ok_packet()

except Exception:

if reconnect:

self._connect()

return self.ping(False)

else:

raise

Finally got a working solution, might help someone.

from gevent import monkey

monkey.patch_socket()

import logging

import gevent

from gevent.queue import Queue

import pymysql as db

logging.basicConfig(level=logging.DEBUG)

LOGGER = logging.getLogger("connection_pool")

class ConnectionPool:

def __init__(self, db_config, time_to_sleep=30, test_run=False):

self.username = db_config.get('user')

self.password = db_config.get('password')

self.host = db_config.get('host')

self.port = int(db_config.get('port'))

self.max_pool_size = 20

self.test_run = test_run

self.pool = None

self.time_to_sleep = time_to_sleep

self._initialize_pool()

def get_initialized_connection_pool(self):

return self.pool

def _initialize_pool(self):

self.pool = Queue(maxsize=self.max_pool_size)

current_pool_size = self.pool.qsize()

if current_pool_size < self.max_pool_size: # this is a redundant check, can be removed

for _ in xrange(0, self.max_pool_size - current_pool_size):

try:

conn = db.connect(host=self.host,

user=self.username,

passwd=self.password,

port=self.port)

self.pool.put_nowait(conn)

except db.OperationalError, e:

LOGGER.error("Cannot initialize connection pool - retrying in {} seconds".format(self.time_to_sleep))

LOGGER.exception(e)

break

self._check_for_connection_loss()

def _re_initialize_pool(self):

gevent.sleep(self.time_to_sleep)

self._initialize_pool()

def _check_for_connection_loss(self):

while True:

conn = None

if self.pool.qsize() > 0:

conn = self.pool.get()

if not self._ping(conn):

if self.test_run:

self.port = 3306

self._re_initialize_pool()

else:

self.pool.put_nowait(conn)

if self.test_run:

break

gevent.sleep(self.time_to_sleep)

def _ping(self, conn):

try:

if conn is None:

conn = db.connect(host=self.host,

user=self.username,

passwd=self.password,

port=self.port)

cursor = conn.cursor()

cursor.execute('select 1;')

LOGGER.debug(cursor.fetchall())

return True

except db.OperationalError, e:

LOGGER.warn('Cannot connect to mysql - retrying in {} seconds'.format(self.time_to_sleep))

LOGGER.exception(e)

return False

# test (pytest compatible) -------------------------------------------------------------------------------------------

import logging

from src.py.ConnectionPool import ConnectionPool

logging.basicConfig(level=logging.DEBUG)

LOGGER = logging.getLogger("test_connection_pool")

def test_get_initialized_connection_pool():

config = {

'user': 'root',

'password': '',

'host': '127.0.0.1',

'port': 3305

}

conn_pool = ConnectionPool(config, time_to_sleep=5, test_run=True)

pool = conn_pool.get_initialized_connection_pool()

# when in test run the port will be switched back to 3306

# so the queue size should be 20 - will be nice to work

# around this rather than test_run hack

assert pool.qsize() == 20

Well, I've got the same problem in my application and I found a method on PyMySQL documentation that pings to the server and verify if the connection was closed or not, if it was closed, then it reconnects again.

from pymysql import connect

from pymysql.cursors import DictCursor

# create the connection

connection = connect(host='host', port='port', user='user',

password='password', db='db',

cursorclass=DictCursor)

# get the cursor

cursor = connection.cursor()

# if the connection was lost, then it reconnects

connection.ping(reconnect=True)

# execute the query

cursor.execute(query)

I hope it helps.

Seth Connell

The easiest way is to check the connection right before sending a query.

You can do this by creating a small class that contains two methods: connect and query:

import pymysql

import pymysql.cursors

class DB:

def connect(self):

self.conn = pymysql.connect(

host=hostname,

user=username,

password=password,

db=dbname,

charset='utf8mb4',

cursorclass=pymysql.cursors.DictCursor,

port=3306)

def query(self, sql):

try:

cursor = self.conn.cursor()

cursor.execute(sql)

except pymysql.OperationalError:

self.connect()

cursor = self.conn.cursor()

cursor.execute(sql)

return cursor

db = DB()

Now, whenever you send a query using db.query("example SQL") the request is automatically prepared to encounter a connection error and reconnects using self.connect() if it needs to.

Remember: This is a simplified example. Normally, you would want to let PyMySQL help you escape special characters in your queries. To do that, you would have to add a 2nd parameter in the query method and go from there.

the logic is quite simple, if connection close then try to reconnect for several times in this case I use max tries for 15 times to reconnect or ping.

import pymysql, pymysql.cursors

conn = pymysql.connect(

host=hostname,

user=username,

password=password,

db=dbname,

charset='utf8mb4',

cursorclass=pymysql.cursors.DictCursor,

)

cursor = conn.cursor()

# you can do transactions to database and when you need conn later, just make sure the server is still connected

if conn.open is False:

max_try = 15

try = 0

while conn.open is False:

if try < max_try:

conn.ping() # autoreconnect is true by default

try +=1

# check the conn again to make sure it connected

if conn.open:

# statements when conn is successfully reconnect to the server

else:

# it must be something wrong : server, network etc

来源:https://stackoverflow.com/questions/22699807/python-mysql-using-pymysql-auto-reconnect

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mysql auto reconnect_Python mysql (using pymysql) auto reconnect 的相关文章

  • 2023年数维杯数学建模A题河流-地下水系统水体污染研究求解全过程文档及程序

    2023年数维杯数学建模 A题 河流 地下水系统水体污染研究 原题再现 河流对地下水有着直接地影响 当河流补给地下水时 河流一旦被污染 容易导致地下水以及紧依河流分布的傍河水源地将受到不同程度的污染 这将严重影响工农业的正常运作 社会经济的
  • 【BZOJ3309】DZY Loves Math(莫比乌斯反演)

    题面 求 i 1a j 1bf gcd a b sum i 1 a sum j 1 bf gcd a b 其中 f x f x 表示 x x分解质因数之后 最高的幂次 题解 完全不会莫比乌斯反演了 先来推式子 d 1a i 1a d j 1
  • 编码器的参数设置

    编码器参数设置 sps pps enc ctx gt profile FF PROFILE H264 HIGH 444 enc ctx gt level 50 表示LEVEL是5 0 enc ctx gt width 640 enc ctx
  • exchange2010 删除特定情况的邮件,转

    一 从Exchange Server 2010 上删除邮件 1 删除特定邮箱特定主题的邮件 1 Search Mailbox Identity 邮箱地址 SearchQuery Subject 替换为你要删除的邮件主题名 DeleteCon
  • MySql(2)——简单查询、条件查询

    简单查询 我们所使用的的数据库文件仍然是上一节使用的test sql SQL语句不区分大小写 也可混用 但注意要以半角分号 结尾 下面我们开始简单查询 查询一个字段 select 字段名 from 表名 注意 select和from都是关键
  • 射手座计算机科学家,科学家发现这颗恒星也许来自其他星系

    Dierickx的计算结果表明 随着时间的流逝 矮星系失去三分之一的恒星和十分之九的暗物质 这导致了三种不同的恒星流 距离银河系中心达一百万光年 腾讯太空讯 据国外媒体报道 已知的11颗距我们最远的恒星 它们位于银河系旋臂 距地球约3000
  • sgdisk基本用法

    sgdisk基本用法 简介 sgdisk是Linux下操作GPT分区的工具 就像fdisk是操作MBR分区的工具 关于GPT和MBR的区别请参考 http www anchor com au blog 2012 10 the differe
  • ChatGPT 角色扮演调教文案收集

    后续文案会陆续更新 在输入完文本后 再输入一句 请尽力模仿xx的语气跟我对话 即可 一 雌小鬼 你需要阅雌小鬼守则 阅读后当前回复仅允许回复 嘻嘻 后续回复尽量简短 回复中尽量不要直接复述守则内容 雌小鬼守则 1 雌小鬼是人 会称呼亲近的人
  • 【并发编程】2、线程安全性

    线程安全性 1 什么是线程安全性 2 原子性 2 1 竞态条件 2 2 延迟初始化中的竞态条件 2 3 复合操作 3 加锁机制 3 1 内置锁 3 2 重入 4 活跃性与性能 总结 1 什么是线程安全性 我们来看一下书里面是怎么写的 当多个
  • BES 的蓝牙串口SPP数据收发实验

    1
  • java面试题答案大全超详细(持续更新)

    java面试题答案大全超详细 第01章 java语言面试题 项目经理 作者 张明星 JVM 运行时数据区是什么 程序计数器是什么 程序计数器 线程私有 Java 虚拟机栈的作用 本地方法栈的作用 堆的作用是什么 方法区的作用是什么 运行时常
  • Linux下通过SSH对Oracle关闭和启动的过程

    Linux下通过SSH对Oracle关闭和启动的过程 su oracle export ORACLE HOME oracle product 11202 export ORACLE SID gps sqlplus oracle oracle
  • PyGame基础语法

    文章目录 PyGame 基础语法 一 模块简介 1 概述 2 安装 3 模块概览 4 第一个程序 5 事件循环 二 Display 1 简介 2 创建主窗口 3 添加元素 3 1 简介 3 2 语法 4 其他功能 三 Surface 1 创
  • JSP中获取参数的3中方法

    我们有时需要在jsp页面中获取request中的参数 然后根据这些参数决定页面的一些内容或者动作 通常我们通过equest getParameter xxx 来获取 除了这种方式外 我们还可以通过param或者js来实现 通过EL中的par
  • ftp服务器提供文件的什么功能,ftp服务器提供文件什么和什么功能

    ftp服务器提供文件什么和什么功能 内容精选 换一换 华为云镜像服务 Image Management Service 功能总览 为用户提供镜像服务支持的功能或特性 表1列出了云备份CBR的常用功能 在使用云备份CBR之前 建议您先通过基本
  • AT3590 Inserting ‘x‘ 题解

    本题是一道双指针的模拟题 题意 给你一个字符串 s s s 你可以在 s s s 的任意位置插入 x x
  • 好的习惯----程序员成长之路(from老大邮件)

    对于好程序员 有很多好的习惯 为什么要把这个习惯放在第一个呢 有很多人如果阅读过 高效能人士的七个习惯 其中第一个习惯就是积极主动 如果从这个角度来看 我把解决解决每一个问题放在首位从理论上是完全没问题的 但我要说说我们程序员独特的地方 所

随机推荐

  • [4G+5G专题-133]: 部署 - 4G/5G常见的室内部署方案

    作者主页 文火冰糖的硅基工坊 文火冰糖 王文兵 的博客 文火冰糖的硅基工坊 CSDN博客 本文网址 https blog csdn net HiWangWenBing article details 121554032 目录 第1章 概述
  • 总结】python sklearn模型中random_state参数的意义

    这是在决策树CART模型时 遇到的 random state 是为了固定随机状态的 主要用在随机数据集 数据集的随机划分 设置决策树模型参数 设置随机森林模型参数 random state 取值大小可以是任意一个整数 在调参缓解 只要保证其
  • 基于Docker的JMeter分布式压测实战讲解

    一个JMeter实例可能无法产生足够的负载来对你的应用程序进行压力测试 如本网站所示 一个JMeter实例将能够控制许多其他的远程JMeter实例 并对你的应用程序产生更大的负载 JMeter使用Java RMI 远程方法调用 来与分布式网
  • 即将离开CSDN,转其他平台

    CSDN的几大作死操作 1 同质化太特么严重了 博客抄来抄去的 内容审核形同虚设 经常搜一个问题 从第一条到最后一条都是一模一样的内容 2 资源付费 资源付费本身是没有任何问题的 但是CSDN里面有几个有用的资源 很多大家花了钱一下载 发现
  • windows凭据密码怎么查看_管理Windows访问凭证,快速访问局域网上的共享资源

    内部网访问其他电脑的共享资源 基本上需要输入访问对方电脑资源允许的账号和密码 在第一次的访问中选择保存凭据后 以后访问就不要输入相应的账号和密码了 但也会出现因修改相关的访问密码或者取消了访问账号的改变 这样就会出现凭据失效的情况 下面介绍
  • 类似-Xms、-Xmn这些参数的含义:

    类似 Xms Xmn这些参数的含义 答 堆内存分配 JVM初始分配的内存由 Xms指定 默认是物理内存的1 64 JVM最大分配的内存由 Xmx指定 默认是物理内存的1 4 默认空余堆内存小于40 时 JVM就会增大堆直到 Xmx的最大限制
  • Python通过ARIMA模型进行时间序列分析预测

    ARIMA模型预测 时间序列分析预测就是在已有的和时间有关的数据序列的基础上构建其数据模型并预测其未来的数据 例如航空公司的一年内每日乘客数量 某个地区的人流量 这些数据往往具有周期性的规律 如下图所示 有的数据呈现出简单的周期性循环 有的
  • Linux嵌入式学习---c语言之循环结构

    Linux嵌入式学习 c语言之循环结构 一 while语句循环 1 1一般形式 1 2累加求和 二 do while语句循环 2 1do while语句一般形式 2 2do while语句特点 三 for语句循环 3 1for语句的一般形式
  • vue-resource请求数据的使用方法

    vue resource vue js关于客户端请求数据的官方插件 使用vue resource请求数据的步骤 1 安装vue resource插件 记得添加 save 若安装淘宝镜像用cnpm npm install vue resour
  • [蓝桥杯2023初赛] 整数删除

    给定一个长度为 N 的整数数列 A1 A2 AN 你要重复以下操作 K 次 每次选择数列中最小的整数 如果最小值不止一个 选择最靠前的 将其删除 并把与它相邻的整数加上被删除的数值 输出 K 次操作后的序列 输入格式 第一行包含两个整数 N
  • vscode:visual studio code 调试php

    简介 php是动态语言没有调试器的话排错起来很是麻烦 vscode可以说是程序员的福音 启动速度快 插件越来越多 跨平台 现在说一下vscode上调试php文件 所需文件 xampp 集成服务器 vscode Xdebug php debu
  • Rightware的Kanzi界面很快你的全液晶汽车仪表盘

    锋影 e mail 174176320 qq com 这是一个屏幕在行动的Kanzi UI编辑器 这是说 汽车仪表板没有显著在过去的几十年里发展公平 不知怎么的 我觉得喜欢的东西是会改变的 但什么也没做 至少在一个大的方式 当日产GTR天际
  • 面试必问的Spring IoC与Spring AOP面试题,你能get到几问?

    Spring IoC Q1 IoC 是什么 Q2 IoC 容器初始化过程 Q3 依赖注入的实现方法有哪些 Q4 依赖注入的相关注解 Q5 依赖注入的过程 Q6 Bean 的生命周期 Q7 Bean 的作用范围 Q8 如何通过 XML 方式创
  • (含源码)「自然语言处理(NLP)」RoBERTa&&XLNet&&语言模型&&问答系统训练

    来源 AINLPer 微信公众号 每日更新 编辑 ShuYini 校稿 ShuYini 时间 2020 07 27 引言 本次内容主要包括 稳健优化Bert模型 RoBERTa 自回归预训练模型 XLNet 无监督多任务学习语言模型 生成预
  • 【BT 协议】HFP 协议

    原文链接 https blog csdn net shichaog article details 52123439 HFP Hands free Profile 让蓝牙设备可以控制电话 如接听 挂断 拒接 语音拨号等 拒接 语音拨号要视蓝
  • C++:智能指针及其实现原理

    更多C 知识点 C 目录索引 1 RAII思想 定义一个类来封装资源的分配与释放 构造函数中完成资源的分配及初始化 析构函数中完成资源的清理 可以保证资源的正确初始化和释放 如果对象是用声明的方式在栈上创建局部对象 那么RAII机制就会正常
  • 从 MySQL 到 OBOracle:如何处理自增列?

    业务需要将数据库转换为 OceanBase 数据库 但源端涉及到 Oracle 及 MySQL 两种不同数据库 需要合并为 OceanBase 中单一的 Oracle 模式 其中源端 MySQL 数据库需要改造为 OB Oracle 并做异
  • 天梯题集——复数四则运算(fabs)

    复数四则运算 include
  • K8S kube-proxy- iptable模式实现原理分析

    每台机器上都运行一个kube proxy服务 它监听api server 和endpoint变化情况 维护service和pod之间的一对多的关系 通过iptable或者ipvs为服务提供负载均衡的能力 通常kube proxy作为deem
  • mysql auto reconnect_Python mysql (using pymysql) auto reconnect

    I m not sure if this is possible but I m looking for a way to reconnect to mysql database when the connection is lost Al