Tips for Solving the 2027 Malformed Packet Error in MySQL

Django MySQL
2022-09-11 18:58 (2 years ago) ytyng

Summary

When executing raw SQL in Django, a specific SQL query

  File "<my-project>/.venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (2027, 'Malformed packet')

caused an error.

Environment

django = "==3.2.15"
mysqlclient = "==2.0.3" (also confirmed to occur with 2.1.1)

Reproduction Code

The code that causes the issue is as follows:

with connections['default'].cursor() as cursor:
sql = """SELECT status_id FROM order_status
WHERE order_status_name IN ("入金済み", "完了")"""
cursor.execute(sql)
print(cursor.fetchall())

At this point, this SQL completes although the result is not as expected, and upon executing the next SQL

django.db.utils.OperationalError: (2027, 'Malformed packet')

this error occurs.

Solution

SELECT status_id FROM order_status
WHERE order_status_name IN ("入金済み", "完了")

For this SQL statement,

order_status\nWHERE

add a half-width space before or after the newline, or

"入金済み", "完了"

change these double quotations to single quotations. This prevents the error from occurring.

In MySQL, it is advisable to avoid using double quotations.

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011