【问题标题】:Fetching huge data from Oracle in Python在 Python 中从 Oracle 获取大量数据
【发布时间】:2013-10-08 09:12:34
【问题描述】:

我需要在 python 2.6 中从 Oracle(使用 cx_oracle)获取大量数据,并生成一些 csv 文件。

数据大小约为 400k 记录 x 200 列 x 100 个字符。

最好的方法是什么?

现在,使用以下代码...

ctemp = connection.cursor()
ctemp.execute(sql)
ctemp.arraysize = 256
for row in ctemp:
  file.write(row[1])
  ...

...脚本在循环中保持数小时,并且没有任何内容写入文件...(有没有办法为提取的每条记录打印一条消息?)

注意:我对 Oracle 没有任何问题,在 SqlDeveloper 中运行查询非常快。

谢谢你,吉安

【问题讨论】:

  • “有没有办法打印消息”....是的,在您的代码中添加一个打印语句...
  • 你的代码中有file.flush()或类似的吗?

标签: python oracle file cx-oracle


【解决方案1】:

您应该改用cur.fetchmany()。 它将获取由 arraysise (256) 定义的行块

Python 代码:

def chunks(cur): # 256
    global log, d
    while True:
        #log.info('Chunk size %s' %  cur.arraysize, extra=d)
        rows=cur.fetchmany()

        if not rows: break;
        yield rows

然后在 for 循环中进行处理;

for i, chunk  in enumerate(chunks(cur)):
            for row in chunk:
                     #Process you rows here

这正是我在TableHunter for Oracle 中的做法。

【讨论】:

    【解决方案2】:
    • 在每一行之后添加打印语句
    • 在循环中添加一个计数器,指示每 N 行之后的进度
    • 查看类似“progressbar”的模块以显示进度指示器

    【讨论】:

    • 你听说过pdb吗?比使用print 好多了
    【解决方案3】:

    我认为您的代码一次向数据库询问一行数据,这可能解释了速度缓慢。

    试试:

    ctemp = connection.cursor()
    ctemp.execute(sql)
    Results = ctemp.fetchall()
    for row in Results:
        file.write(row[1])
    

    【讨论】:

    • 先取800兆到内存,再写入文件?可以工作,但我不想这样做。
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多