dbf与大多数其他数据库包的不同之处在于,您不是直接使用dbf文件本身而是获得完全独立的数据结构(例如,一串行作为元组).
我发现自己遇到的问题是,当我一次更新多个字段时:
record.name = 'Some Name'
record.age = current_year -birth_year
record.hair_color = base_color * sun_tint
如果在第一个字段之后的任何时间发生错误,我的记录只是部分更新,因此不再内部一致.
为了解决这个问题,我添加了一些代码,它类似于基于每个记录的提交,并且激活它的方式是使用或使用Process:
with record: # capture current values
record.field1 = something
record.field2 = something_else
record.field3 = another_thing
# now some other code
现在,如果发生错误,则恢复原始值;如果没有错误,则新值将保存到磁盘上的dbf表中.
除了记录之外,您还可以在一堆记录上使用Process,或者您可以避免问题并在记录之外收集数据,然后立即写入:
for record in table:
new_data = {}
new_data['field1'] = 'a name'
new_data['field2'] = an_age
dbf.write(record, new_data)
因此,要回到您的代码,修复它的最简单方法可能是:
with dbf.Table("aa.dbf") as table:
for record in dbf.Process(table):
record[3] = 200