Мой код Python ниже показывает мою попытку разделить запрос на фрагменты (с использованием смещения/предела), чтобы обслуживать память, как это было бы крушение без этого код работает, но выглядит очень медленно (занимает около 30 минут) по сравнению с выполнением полного запроса без смещения/ограничения в браузере запросов sql, таком как рабочая среда MYSQL (занимает около 4 минут).
Код: Выделить всё
def mysql_query():
chunk_size = 1000000
offset = 0
ndate = date()
db = mysql_dbconnection()
print("Executing SQL query")
cur = db.cursor()
print("Writing output to file")
### Create File & Write Records To File
with open(args["dpath"] + args["dfile"] + "." + args["ext"], "w", encoding = 'utf8') as feed_file:
# Open SQL File for Reading
with open((args["sqlsfile"]), 'r') as file:
query = " ".join(file.readlines())
print(query)
cur.execute(f"{query} LIMIT 1")
cur.fetchone()
### Get Field Names
field_tupple = [i[0] for i in cur.description]
field_names = '\t'.join(field_tupple)
#print(field_names)
# Write main header
feed_file.write("EDI_Test_" + ndate + '\n')
# Write field headers
feed_file.write(field_names + '\n')
while True:
cur.execute(f"{query} LIMIT {chunk_size} OFFSET {offset}")
#print(f"{query} LIMIT {chunk_size} OFFSET {offset}")
### Get Records
records = cur.fetchall()
if not records:
break
for record in records:
for r in record:
d = {None: ''}
record = [d.get(x, x) for x in record]
r = '\t'.join([str(x) for x in record if x is not None])
#print(r)
feed_file.write(r + '\n')
offset += chunk_size
print(offset)
# Write footer
feed_file.write("EDI_ENDOFFILE")
# Commit the changes to the database
cur.close()
db.close()
Есть существует более оптимальный, эффективный и быстрый способ разделить большой SQL-запрос на куски и запись в файл в Python/MYSQL?
Подробнее здесь: https://stackoverflow.com/questions/792 ... -and-mysql