问题
Code:
#!/usr/bin/python
db = dbf.Dbf("MEST2.DBF")
#LINE TO UPDATE:
rec = db[0]
#PROEST IS A field of my dbf. I'm assigning 1 to this field line 0
rec["PROEST"] = 1
rec.store()
del rec
db.close()
IMAGE OF DBF TABLE: http://i.stack.imgur.com/1UHE1.jpg
My problem is I can not change the records by rows, cause the position of the products (PROCOD) may vary.
Any suggestions to get the PROCOD and change the value of PROEST?
UPDATED:
#!/usr/bin/python
import dbf
db = dbf.Table('MEST2.DBF')
with db:
procod_idx = db.create_index(lambda rec: (rec.codigo, rec.procod))
match = procod_idx.search(match='000001')
# should only be one product with that code
record = match[0]
with record:
record.proest = 23
But the question now is, how i edit the value based on the CODIGO field (Stock code). I have multiples stocks ID: (1, 2, 5, 11). The code update just the first result, i need update a specific record based in the CODIGO FIELD.
In SQL would be: "UPDATE PROEST SET 32 where CODIGO=11"... or CODIGO=2
SOLVED by Ethan Furman
#!/usr/bin/python
import dbf
db = dbf.Table('MEST2.DBF')
with db:
procod_idx = db.create_index(lambda rec: (rec.codigo, rec.procod))
match = procod_idx.search(match=(11, '000001'))
record = match[0]
with record:
record.proest = 25
record.dt_atualiz = '14/07/15 16:52'
回答1:
You don't say which dbf
package you are using, but it looks like mine.
What you want to do is create an temporary index on the PROCOD
field and then you can search on it and update whichever other fields you need to:
# untested
import dbf
db = dbf.Table('MEST2.DBF')
with db:
procod_idx = db.create_index(lambda rec: rec.procod)
# get a list of all matching records
match = procod_idx.search(match='000001')
# should only be one product with that code
record = match[0]
with record:
record.proest = ...
record.dt_atualiz = ...
If the product code is not unique, then the above "should only be one product with that code comment" is wrong.
Change the index to:
procod_idx = db.create_index(lambda rec: (rec.codigo, rec.procod))
and then search with:
match = procod_idx.search(match=(11, '000001'))
record = match[0]
...
match = procod_idx.search(match=(2, '000001'))
record = match[0]
...
来源:https://stackoverflow.com/questions/31409565/search-in-dbf-and-update-record