I'm trying to write some code in python (2.7) doing this:
- Open a database in sqlite
- Do a query to the database, getting some results. The database has more than one table and i need the records from different tables:
database is like this:
- data.db ---> [table1[col1, col2, col3], table2[col1, col2, col3]]
- Iterate through the results
- Do something on the results (for exaple in a record there is a date that need decoding)
- Store all the records in a namedtuple for further access
Since now i have achieved part 1, 2, 3 and 4, but i can't figure out how to store the results in a namedtuple. Assume that on every iteration i store the data that i need in the namedtuple in temporary variables:
for result in results:
var1 = table1.col1
var2 = table2.col1
var3 = table3.col1
(now i want to do something with the variable, but thats' not the problem, and store the 3 variables in a namedtuple)
contacts = namedtuple('contacts', 'Z_PK ZFULLNAME ZPHONE ZTEXT ZDATE')
if has_contacts_sqlite:
# reading contacts from database
# 1st step: ZWAPHONE table
query = "SELECT * FROM ZWAPHONE"
self.tempcur.execute(query)
tempcontacts = self.tempcur.fetchall()
for contact in tempcontacts:
id = contact.Z_PK
contact_key = contact.ZCONTACT
favorite_key = contact.ZFAVORITE
status_key = contact.ZSTATUS
phonenum = contact.ZPHONE
# 2nd step: name from ZWACONTACT table
query = "SELECT * FROM ZWACONTACT WHERE Z_PK=?;"
self.tempcur.execute(query, [contact_key])
contact_entry = self.tempcur.fetchone()
if contact_entry == None:
name = "N/A"
else:
name = contact_entry.ZFULLNAME
# 3rd step: status from ZWASTATUS table
query = "SELECT * FROM ZWASTATUS WHERE Z_PK=?;"
self.tempcur.execute(query, [status_key])
status_entry = self.tempcur.fetchone()
if status_entry == None:
text = "N/A"
date = "N/A"
else:
text = status_entry.ZTEXT
date = self.formatDate(status_entry.ZDATE)
#print ("%s" %(id))
#print ("%s" %(name.encode(sys.stdout.encoding, errors='replace')))
#print ("%s" %(phonenum.encode(sys.stdout.encoding, errors='replace')))
#print ("%s" %(text.encode(sys.stdout.encoding, errors='replace')))
#print ("%s" %(date))
contact = contacts(id, name, phonenum, text, date)
print contacts
for line in contacts:
print line