How to convert a "SQLite3 object cursor" to a list (Python)

0

In a cell of a table in my database I have a list of pairs. I have a Python module that I want to go fetch this list from the database and read it as a list. I tried to run this:

interpretation = db.execute("SELECT interpretation FROM music WHERE ID = ?", (id, ))

I have tried to list(interpretation) , eval(interpretation) , send the list to the database converted in JSON, and decode in the module that will get those values, but nothing worked. The problem is therefore simple: I want my interpretation , which is interpreted as a "SQLite3 object cursor" to be interpreted as being a list.

    
asked by anonymous 26.05.2015 / 23:19

1 answer

1

Calling the execute method - either from a connection to the database or from a cursor object in Python does not return the results immediately. This is done on purpose, so it is easier to create applications where the bank works asynchronously. (Not the case of SQLite, which runs in the same process - but other banks are triggered by the network layer, and may be returning lazy values)

To retrieve the results of a query, use the methods fetch and fetchall - or you can simply use the cursor as iterator for : it returns the results:

cursor = db.cursor()
cursor.execute("SELECT interpretation FROM music WHERE ID = ?", (id, ))
for result in cursor:
   print(result)[0]

(In this case, the result is a tuple with the values returned in each row of the query. If the query should return 16 columns, a tuple containing the 16 values will be set with indexes between 0 and 15) p>

If you just want to throw the values in a data structure, as you are in the question - it's a little less efficient than using direct for (mainly because you will temporarily duplicate the data in memory) - should be able to do simply:

cursor = db.execute(...)
results = list(cursor)  

As you put it. But each element of the list is a tuple, with all your results - even if you only have one column. So it's a tuple with a single element - and you can extract it with the list comprehension syntax like this:

results = [line[0] for line in cursor]
    
27.05.2015 / 15:32