gpt4 book ai didi

Python:将大型 SQL Server 查询结果导出到 .txt 文件

转载 作者:行者123 更新时间:2023-12-01 09:33:52 25 4
gpt4 key购买 nike

将超过 600,000,000 行的 SQL Server 查询结果复制到本地 .txt 文件中,性能和内存效率最高的方法是什么?您可能会认为我没有从 SQL Server Management Studio 导出的用户权限。因此,Python 似乎是我的最佳选择。

我目前正在使用 Python pyodbc 包:

connection = pyodbc.connect('Driver=DRIVER;' \
'Server=SERVER;' \
'Database=DATABASE;' \
'uid=USERNAME;' \
'pwd=PASSWORD')

cursor = connection.cursor()
try:
cursor.execute("SELECT * FROM %s" % table)
except:
print('===== WAITING ===== EXECUTE ERROR =====')
time.sleep(15)
cursor.execute("SELECT * FROM %s" % table)

try:
data = cursor.fetchall()
except:
print('===== WAITING ===== FETCH ERROR =====')
time.sleep(15)
data = cursor.fetchall()

with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=delimiter)
writer.writerow([x[0] for x in cursor.description]) # column headers
for row in data:
writer.writerow(row)
cursor.close()

旁注:我的目标是将数百个 SQL 表作为 .txt 文件传输到 Amazon S3 存储桶。有没有更好的方法来做到这一点,而不是将文件下载到本地驱动器,然后上传到 S3?

最佳答案

这取决于结果集,但作为一般规则,我会使用 fetchmany 一次抓取一堆行,而不是将所有内容拉入内存:

fetch_rows = 1000
rows = cursor.fetchmany(fetch_rows)
while rows is not None:
for row in rows:
do_something()
rows = cursor.fetchmany(fetch_rows)

祝你好运!

关于Python:将大型 SQL Server 查询结果导出到 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49703417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com