用Python有效查询DBF文件

问题描述

我需要从旧版 VFP DBF 数据库中读取数据,并收集当前一周内具有 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 文件的更有效方法是什么?

解决方法

如您所知,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 物理排序时才有效。