在Python中从Oracle获取大量数据

时间:2013-10-08 09:12:35

标签: python oracle file cx-oracle

我需要在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中运行查询速度非常快。

谢谢你,吉安

3 个答案:

答案 0 :(得分: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中的表现。

答案 1 :(得分:0)

  • 在每行之后添加打印语句
  • 在循环中添加一个计数器,指示每N行后的进度
  • 查看“进度栏”等模块,以显示进度指示器

答案 2 :(得分:0)

我认为你的代码正在向数据库询问当前一行的数据,这可能解释了这一点。

尝试:

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