Python中Django使用MySQL原生查询时卡住怎么办?

django2.0 开发项目,有人用模型,有人用 mysql 原生写,django 里面 mysql 原生写的代码不跟随数据库更新,重新启动 django 后数据才会更新,求个解决办法
Python中Django使用MySQL原生查询时卡住怎么办?

4 回复

看看是不是事务没有提交


遇到Django执行MySQL原生查询卡住,通常有几个常见原因和解决方法:

1. 检查连接和事务

from django.db import connection

# 检查当前连接状态
print(connection.connection.ping(reconnect=True))  # 测试连接

# 如果是事务问题,尝试设置自动提交
from django.db import connection, transaction
with transaction.atomic():
    # 你的查询代码
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM your_table LIMIT 1")
        row = cursor.fetchone()

2. 设置查询超时

from django.db import connection
import signal

class TimeoutException(Exception):
    pass

def timeout_handler(signum, frame):
    raise TimeoutException("Query timeout")

# 设置10秒超时
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(10)

try:
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM large_table")
        results = cursor.fetchall()
except TimeoutException:
    print("查询超时")
finally:
    signal.alarm(0)  # 取消定时器

3. 优化查询语句

  • 检查是否有全表扫描:添加合适的索引
  • 避免SELECT *,只选择需要的字段
  • 使用EXPLAIN分析查询计划

4. 使用分页查询大数据

def batch_query(query, batch_size=1000):
    with connection.cursor() as cursor:
        cursor.execute(query)
        while True:
            rows = cursor.fetchmany(batch_size)
            if not rows:
                break
            yield rows

# 使用示例
for batch in batch_query("SELECT * FROM huge_table"):
    process_batch(batch)

5. 检查MySQL服务器状态

# 查看当前进程
with connection.cursor() as cursor:
    cursor.execute("SHOW PROCESSLIST")
    processes = cursor.fetchall()
    for process in processes:
        print(process)

快速排查步骤:

  1. 先在MySQL客户端直接运行相同查询,看是否卡住
  2. 检查表锁:SHOW OPEN TABLES WHERE In_use > 0
  3. 查看慢查询日志
  4. 检查网络连接和防火墙设置

建议先加个查询超时和分页处理。

楼主说的什么乱七八糟的?
SQL 插在代码里面,当然要重起进程才能生效。

楼主说的用 mysql 原生写是直接用的 pymysql 接口直接写的,还是用的 django 的 db.connection?

回到顶部