2016-05-13 136 views
1

我想连接到mysql数据库以检索某些用户的id并使用这些id从另一个表中检索另一组数据。它应该很容易,但我得到的MySQL错误。这是我正在尝试做的一个片段。尝试使用Python连接到mysql时获取2013失去的连接错误

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条记录也是如此。

+0

什么是服务器的错误日志说?您可能需要激活或增加日志级别。 –

+0

@KlausD。我没有错误日志。我没有数据库的管理员权限。我只是想知道是否是第二次连接到mysql时使用相同的连接的问题。 – Cryssie

+0

然后你应该与管理员联系。 –

回答

0

关于你的第二部分,你可能不执行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) 
+0

谢谢。其实这是我的错字。我正在重写问题中的代码,并错过了这一部分。它仍然无法与加入的执行行一起工作。 – Cryssie

+0

'user'表中有多少条记录?你的'user_contact'表中有多少条用户id为''的记录? – Blank

+0

这是一个粗略的估计,但也许是三千万。即使将每个记录的检索数限制为只有100个,相同的代码仍然失败,并且在使用mysqlyog查询时只需不到1秒。 – Cryssie