【问题标题】:Getting 2013 lost connection error when trying to connect to mysql with Python尝试使用 Python 连接到 mysql 时出现 2013 丢失连接错误
【发布时间】:2016-05-13 03:25:37
【问题描述】:

我正在尝试连接到 mysql 数据库以检索某些用户的一些 id,并使用这些 id 从另一个表中检索另一组数据。这应该很容易,但我收到 mysql 错误。这是我正在尝试做的事情。

import MySQLdb
from langdetect import detect

my_db = MySQLdb.connect(
                    host="localhost", 
                    port = 3306,
                    user="user", 
                    passwd="password",
                    db="mydb",
                    charset = 'utf8'
                    )

sql1 = """SELECT id, comment FROM users WHERE usertype = 5 LIMIT 100"""

users = []
db_cursor = my_db.cursor()
db_cursor.execute(sql1)
users = db_cursor.fetchall()

sql2 = """SELECT first_name, last_name, email FROM user_contact WHERE id = %s"""

user_contact =[]
for user in users:
    comment = user[1]
    if detect(comment) == 'en': 
        id = user[0]
        db_cursor = my_db.cursor()
        db_cursor.execute(sql2, (id))
        temp = db_cursor.fetchall()
        user_contact . append (temp)

print (user_contact)

这是我尝试运行此查询时收到的错误消息。

_mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

查询的第一部分通常会通过,但在第二部分尝试再次连接到 mysql 时通常会失败。我只测试了 100 条记录,只是为了检查是否是查询运行时间过长的问题,但即使有 10 条记录,它仍然是一样的。

【问题讨论】:

  • 服务器的错误日志是怎么说的?您可能需要激活 is 或提高日志级别。
  • @KlausD。我没有错误日志。我没有数据库的管理员权限。我只是想知道第二次使用相同的连接连接到mysql是否有问题。
  • 那你应该联系管理员了。

标签: python mysql mysql-error-2013


【解决方案1】:

对于您的第二部分,您可能不会执行 sql;)

尝试改变

for user in users:
    comment = user[1]
    if detect(comment) == 'en': 
        id = user[0]
        db_cursor = my_db.cursor()
        temp = db_cursor.fetchall()
        user_contact . append (temp)

for user in users:
    comment = user[1]
    if detect(comment) == 'en': 
        id = user[0]
        db_cursor = my_db.cursor()
        db_cursor.execute(sql1, (id))
        temp = db_cursor.fetchall()
        user_contact . append (temp)

【讨论】:

  • 谢谢。实际上这是我的错字。我正在重写问题中的代码并错过了那部分。它仍然不适用于添加的执行行。
  • user 表中有多少条记录?您的user_contact 表中有多少条记录,用户为id
  • 这是一个粗略的估计,但可能是 3000 万。即使我将检索到的每条记录的数量限制为仅 100 条,并且使用 mysqlyog 查询它时花费的时间不到 1 秒,相同的代码仍然会失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 2019-06-05
  • 1970-01-01
相关资源
最近更新 更多