【发布时间】:2017-05-29 11:41:45
【问题描述】:
我编写了一个脚本来帮助我使用数据库。具体来说,我正在尝试处理磁盘上的文件并将这项工作的结果添加到我的数据库中。我复制了下面的代码,但删除了大部分与我的数据库无关的逻辑,以尽量保持这个问题的广泛性和帮助性。
我使用代码对文件进行操作并将结果添加到数据库中,覆盖与我正在处理的文件具有相同标识符的所有文件。后来,我修改了脚本以忽略已经添加到数据库中的文档,现在每次运行它都会出错:
pymysql.err.OperationalError: (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")
似乎服务器拒绝了请求,可能是因为我的代码写得不好?我注意到错误总是发生在文件列表中的同一位置,这不会改变。如果我重新运行代码,将文件列表替换为仅包含程序崩溃的文件的列表,则它可以正常工作。这让我觉得在发出一定数量的请求后,数据库才刚刚触底。
我在 OS X 上使用 Python 3 和 MySQL Community Edition 14.14 版。
代码(去掉与数据库无关的东西):
import pymysql
# Stars for user-specific stuff
connection = pymysql.connect(host='localhost',
user='root',
password='*******',
db='*******',
use_unicode=True,
charset="utf8mb4",
)
cursor = connection.cursor()
f_arr = # An array of all of my data objects
def convertF(file_):
# General layout: Try to work with input and add it the result to DB. The work can raise an exception
# If the record already exists in the DB, ignore it
# Elif the work was already done and the result is on disk, put it on the database
# Else do the work and put it on the database - this can raise exceptions
# Except: Try another way to do the work, and put the result in the database. This can raise an error
# Second (nested) except: Add the record to the database with indicator that the work failed
# This worked before I added the initial check on whether or not the record already exists in the database. Now, for some reason, I get the error:
# pymysql.err.OperationalError: (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")
# I'm pretty sure that I have written code to work poorly with the database. I had hoped to finish this task quickly instead of efficiently.
try:
# Find record in DB, if text exists just ignore the record
rc = cursor.execute("SELECT LENGTH(text) FROM table WHERE name = '{0}'".format(file_["name"]))
length = cursor.fetchall()[0][0] # Gets the length
if length != None and length > 4:
pass
elif ( "work already finished on disk" ):
# get "result_text" from disk
cmd = "UPDATE table SET text = %s, hascontent = 1 WHERE name = %s"
cursor.execute(cmd, ( pymysql.escape_string(result_text), file_["name"] ))
connection.commit()
else:
# do work to get result_text
cmd = "UPDATE table SET text = %s, hascontent = 1 WHERE name = %s"
cursor.execute(cmd, ( pymysql.escape_string(result_text), file_["name"] ))
connection.commit()
except:
try:
# Alternate method of work to get result_text
cmd = "UPDATE table SET text = %s, hascontent = 1 WHERE name = %s"
cursor.execute(cmd, ( pymysql.escape_string(result_text), file_["name"] ))
connection.commit()
except:
# Since the job can't be done, tell the database
cmd = "UPDATE table SET text = %s, hascontent = 0 WHERE name = %s"
cursor.execute(cmd, ( "NO CONTENT", file_["name"]) )
connection.commit()
for file in f_arr:
convertF(file)
【问题讨论】:
标签: python mysql python-3.x pymysql