Get Iterator Tuple from SQLite Query

667 views Asked by At

I'm connecting to an SQLite database. When querying the database in python, it returns a tuple object. I prefer to work with namedtuple. The problem is I can't iterate through the object more than once. I'm not sure if the issue is with the way in which I'm creating the object or if it has to do with how I'm assigning the data to the object. Here's what I have:

import sys
import sqlite3
from collections import namedtuple

data = namedtuple('data', 'id, name')
conn = sqlite3.connect('database.db')
c = conn.cursor()

c.execute('SELECT id,name FROM my_table;')
data = map(data._make, c.fetchall())
conn.close()

for id in data: 
    print (table.id)

for id in data:
    print (table.id)

>>>123
>>>456
>>>789

There are only 3 entries in the table right now. So I should get all 3 entries repeated, because of the second loop, but I don't.

I've tried changing some of the lines, similar to what is shown on the Docs page, but it hasn't helped.

1

There are 1 answers

0
user2951249 On BEST ANSWER

As posted by mgilson, data = map(data._make, c.fetchall()) needs to be changed to data = list(map(data._make, c.fetchall())).