Python FDB 将大量数据从数据库保存到文件



我有这个脚本

SELECT = """
            select 
              coalesce (p.ID,'') as id, 
              coalesce (p.name,'') as name, 
            from TABLE as p  
         """
self.cur.execute(SELECT)
for row in self.cur.itermap():         
    id = '%(id)s' % row
    name = '%(name)s' % row
    xml +="  <item>n"      
    xml +="    <id>"         + id + "</id>n"
    xml +="    <name>"    + name + "</name>n"    
    xml +="  </item>nn"
    
#save xml to file here
f = open...
  

我需要将数据从庞大的数据库保存到文件中。我的数据库中有 10 000 个(最多 40000 个)项目,脚本运行需要很长时间(1 小时或更长时间)才能完成。

如何从数据库中获取所需的数据并将其"一次"保存到文件中?(越快越好?我不需要 xml 输出,因为我以后可以在服务器上处理输出中的数据。我只需要尽快完成。知道吗?

非常感谢!

附言我发现了一件有趣的事情:当我使用此代码每 2000 条记录"擦除"xml变量并将其保存到另一个变量时,它的工作速度非常快!因此,根据我以前的代码填写 xml 变量一定有"错误"。

result = float(id)/2000
if result == int(result):
  xml_whole += xml
  xml = ""

哇,用代码测试后

result = float(id)/2000
if result == int(result):
  xml_whole += xml
  xml = ""

我的脚本速度提高了 50 倍!我想知道为什么 Python 使用 XML +=... 这么慢?

你正在做很多不必要的工作(但是,如果你擦除xml变量,你不会像以前那样写入相同的数据......

你为什么不直接编写 XML?你也可以避免两个COALESCE,并在Python中编写该检查(如果ID为空,则使id''等)。

SELECT = """
            select 
              coalesce (p.ID,'') as id, 
              coalesce (p.name,'') as name, 
            from TABLE as p  
         """
self.cur.execute(SELECT)
# Open XML file
f = open("file.xml", ...)
f.write("<?xml version... (what encoding?)
for row in self.cur.itermap():
    f.write("<item>n    <id>%(id)s</id>n    <name>%(name)s</name>n</item>n"
# Other f.writes() if necessary
f.close()

最新更新