PyMysql错误:数据包序列号错误-得到1,预期为0

gwbalxhn  于 2023-10-15  发布在  Mysql
关注(0)|答案(2)|浏览(370)

我在stackoverflow和另一个这个主题讨论的编码示例站点上看到的。但是我找不到任何成熟的解决方案,有人能解决这个错误吗?
错误消息:

ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0
ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0
ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0
ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0
ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0
ERROR:root:Can't connect to to MySQL server with error: (pymysql.err.InternalError) Packet sequence number wrong - got 1 expected 0

连接设置如下:

"mysql+pymysql://{u}:{p}@{s}/{d}?charset=utf8".format(
                u=creds['username'],
                p=creds['password'],
                s=creds['host'],
                d=creds['dbname']
            ),
            pool_recycle=3500,
            echo=False,
            pool_pre_ping=True,
            pool_size=2,
            max_overflow=5
        )
9lowa7mx

9lowa7mx1#

link之后,我得到了:
在使用pymysql和python多线程时,通常我们会面临以下问题:
它不能与所有子线程共享主线程创建的连接。这将导致以下错误:pymysql.err.InternalError:包序列号错误-得到0预期1如果我们让每个子线程创建一个连接,并在这个子线程结束时关闭它,这是可行的,但显然会导致与MySQL建立连接的高成本。
看起来他们已经开发了其他库来解决这个问题:PyMySQL连接池(同一链接)

k4emjkb1

k4emjkb12#

1.安装pymysql-pool

pip3 install pymysql-pool

2.代码导入

import pymysql

import pymysqlpool

3.代码启动时配置

config={'host':'localhost', 'user':'{dbuser}', 'password':'{dbpass}', 'database':'{dbname}', 'autocommit':True}

pool1 = pymysqlpool.ConnectionPool(size=2, maxsize=3, pre_create_num=2, name='pool1', **config)

4.每次查询时

con1 = pool1.get_connection()

gcu = con1.cursor()

gcu.execute("SELECT ....")

myresult = gcu.fetchall()

con1.close()

5.每次提交:

con1 = pool1.get_connection()

gcu = con1.cursor()

sql = "update ..."

gcu.execute(sql)

con1.commit()

con1.close()

所以,这段代码可以永远在没有中断的情况下工作,使用最小的系统 * 资源 *.

相关问题