首页 > 解决方案 > 使用 Python 有效查询 DBF 文件

问题描述

我需要从旧 VFPDBF数据库中读取并收集etd在本周内具有的所有行。

我正在使用dbf,但是似乎在查询表时,它从表中的第一条记录开始查询。这会在尝试查找上周内的数据时导致性能问题,因为它每次运行时都必须遍历数据库中的每一行 (60k+)。


table = dbf.Table(r'\\server\file.dbf')

table.open()

for row in table:

    if (self.monday < row.etd < self.friday) and ('LOC' not in row.route):
        self.datatable.Rows.Add(row.manifest, row.route, row.etd, row.eta, row.inst, row.subname)
    else:
        continue

我试图用“反转”表格for row in table[::-1]:

但是,这需要的时间与我认为它需要在[::-1]

DBF查询这些文件的更有效方法是什么?

标签: pythondbf

解决方案


如您所知,dbf不支持索引文件。但是,它确实有一些类似于 VFP 的方法可以提供帮助:

# untested

table = ...

potental_records = []
with table:               # auto opens and closes
    table.bottom()        # goes to end of table
    while True:
        table.skip(-1)    # move to previous record
        row = table.current_record
        if self.monday > row.etd:
            # gone back beyond range
            break
        elif row.etd < self.friday:
            potential_records.append(row)

# at this point the table is closed and potential_records should have all
# records in the etd range.

仅当记录由 物理订购时,上述方法才有效etd


推荐阅读