Python put Database records in Namedtuple

2019-08-21 05:24发布

问题:

I'm trying to write some code in python (2.7) doing this:

  1. Open a database in sqlite
  2. 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]]
  3. Iterate through the results
  4. Do something on the results (for exaple in a record there is a date that need decoding)
  5. 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

回答1:

A namedtuple() is nothing but a class generated with a factory function:

SomeRowResult = namedtuple('SomeRowResult', 'var1 var2 var3')

Here SomeRowResult is a class object (a subclass of tuple), and calling it will create instances of the class:

for result in results:
    result = SomeRowResult(table1.col1, table2.col1, table3.col1)

If you wanted to have a list of these results, you need to explicitly build that list:

all_results = []
for result in results:
    result = SomeRowResult(table1.col1, table2.col1, table3.col1)
    all_results.append(result)