Tips for Solving the 2027 Malformed Packet Error in MySQL
DjangoMySQL
2022-09-11 09:58 (4 years ago)

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.
Please rate this article (No signup or login required)
Currently unrated
Related posts
How to Fix Display Issues in Django Admin Inlines After Upgrading to 5.1
Return Login and Redirect Views by Hardcoding Social Account Provider in django-allauth (When Using AWS Cognito, etc.)
Here's the English translation of your blog title:"A Story About Trying to JOIN Fields with Different Collations in MySQL and Getting 'Range checked for each record'"
After Upgrading to Django 5 and Updating Dependencies, SSL: CERTIFICATE_VERIFY_FAILED Error Occurs When Sending Emails
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.