You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:MySQL取20条最新记录排序异常及SQLAlchemy连接问题

Hey there! Let's break down your two issues and walk through solutions step by step—happy to help a new programmer get things sorted out.


问题1:记录展示顺序随机,无法按注册时间倒序排列

The core issue here is almost certainly that your database query doesn't specify an explicit sort order. Without an ORDER BY clause, MySQL returns results in an arbitrary (storage-dependent) order, which looks random to you.

Using SQLAlchemy, you just need to add a sort to your query, targeting your registration time field, and limit to the latest 20 records. Here's how to implement it:

Suppose your user model is called User and your registration timestamp field is created_at:

# In your app.py query logic
from your_models import User
from sqlalchemy import desc

# Fetch latest 20 users, sorted by registration time (newest first)
latest_users = User.query.order_by(desc(User.created_at)).limit(20).all()

Then pass latest_users to your HTML template, and loop through it directly—no extra sorting needed in the template:

<!-- In your HTML template -->
{% for user in latest_users %}
  <div class="user-item">
    <p>Username: {{ user.username }}</p>
    <p>Registered: {{ user.created_at.strftime('%Y-%m-%d %H:%M') }}</p>
  </div>
{% endfor %}

This will ensure the most recently registered users appear at the top.


问题2:sqlalchemy.exc.OperationalError (2013, 'Lost connection to MySQL...')

This error happens when your application's connection to MySQL gets dropped unexpectedly. Here are the most common fixes and troubleshooting steps:

  • Fix connection timeouts
    MySQL has a default wait_timeout setting (usually 8 hours) that closes idle connections. To avoid this, add a pool_recycle parameter to your SQLAlchemy connection URL, setting it to a value smaller than MySQL's timeout (e.g., 3600 seconds = 1 hour):

    # Example database URI with pool_recycle
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://your_user:your_password@localhost/your_db?pool_recycle=3600'
    

    You can also explicitly check if a connection is alive before using it:

    from sqlalchemy import create_engine
    
    engine = create_engine(SQLALCHEMY_DATABASE_URI)
    with engine.connect() as conn:
        conn.ping()  # Reconnect if connection is dead
        # Run your queries here
    
  • Adjust connection pool settings
    If your app creates/destroys connections too frequently or runs out of pool connections, tweak these parameters:

    engine = create_engine(
        SQLALCHEMY_DATABASE_URI,
        pool_size=10,  # Number of persistent connections to keep
        max_overflow=20  # Extra connections allowed during traffic spikes
    )
    
  • Check MySQL server & network

    • Verify the MySQL service is running (use systemctl status mysql on Linux, or check Services on Windows).
    • For production environments, check server load, firewall rules, and network stability to rule out external disruptions.
  • Proper connection management
    Always use context managers (with statements) to handle database sessions—this ensures connections are returned to the pool properly and avoids leaks:

    from sqlalchemy.orm import sessionmaker
    
    Session = sessionmaker(bind=engine)
    with Session() as session:
        # Perform your database operations here
        users = session.query(User).all()
    # Session closes automatically when exiting the 'with' block
    

内容的提问来源于stack exchange,提问作者Tshibe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:48:48