【问题标题】:Efficiently reading foxpro DBF with python使用python高效读取foxpro DBF
【发布时间】:2014-07-31 16:57:23
【问题描述】:

我已经尝试了两个模块来读取运行良好的 dbf 文件(dbf 和 dbfpy),但我必须逐条读取数据库以查找内容。这对于大型数据库来说真的很慢。是否有任何模块可以处理查询表或使用 CDX 索引?

【问题讨论】:

  • 根据您的平台,我想您可以尝试操作系统级别的外部接口,例如 ODBC/JDBC。

标签: python foxpro dbf visual-foxpro


【解决方案1】:

我不相信dbfpy 支持索引文件,我知道dbf 不支持。

但是,在dbf 中,您可以创建一个临时索引,然后查询:

big_table = dbf.Table('/path/to/some/big_table')
def criteria(record):
    "index the table using these fields"
    return record.income, record.age
index = big_table.create_index(key=criteria)

index 现在可以迭代或搜索以返回所有匹配记录:

for record in index.search(match=(50000, 30)):
    print record

示例表:

table = dbf.Table('tempu', 'name C(25); age N(3,0); income N(7,0);')
table.open()
for name, age, income in (
        ('Daniel', 33, 55000),
        ('Mike', 59, 125000),
        ('Sally', 33, 77000),
        ('Cathy', 41, 50000),
        ('Bob', 19, 22000),
        ('Lisa', 19, 25000),
        ('Nancy', 27, 50000),
        ('Oscar', 41, 50000),
        ('Peter', 41, 62000),
        ('Tanya', 33, 125000),
        ):
    table.append((name, age, income))

index = table.create_index(lambda rec: (rec.age, rec.income))

还有一些方法可以搜索范围的开始和结束:

# all the incomes of those who are 33
for rec in index.search(match=(33,), partial=True):
    print repr(rec)
print
# all the incomes of those between the ages of 40 - 59, inclusive
start = index.index_search(match=(40, ), nearest=True)
end = index.index_search(match=(60, ), nearest=True)
for rec in index[start:end]:
    print repr(rec)

哪个打印:

Daniel                    33  55000
Sally                     33  77000
Tanya                     33 125000

Cathy                     41  50000
Oscar                     41  50000
Peter                     41  62000
Mike                      59 125000

【讨论】:

  • 这花费了大约两倍的时间。我猜是因为它必须创建索引然后循环遍历它。
  • @user3727436:您可以编辑您的答案并发布您尝试过的代码吗?创建索引确实会遍历整个表一次,但之后(使用正确的习惯用法)查找应该使用二进制算法。
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多