V. Raman
V. Raman

Reputation: 221

Python SQLite3 / Selecting rows from table

board  balls  win1   win2   result
-----  -----  ----   ----   ------
    1      1     0      0        1
    4      1     0      0        1
 1024      1     0      0        1

When we are selecting only one row but multiple columns from a table, for example, by using:

connection = sqlite3.connect("spline.db")
crsr = connection.cursor()
crsr.execute("SELECT board FROM positions WHERE balls = 1")
result = crsr.fetchall()
print result
connection.close()

The result is a list of tuples:

[(1,), (4,), (1024,)]

Is there any way to get a list of integers directly? One way to do it is with:

print [result[i][0] for i in range(len(result))]

instead of with:

print result

But whenever that there are as much as 107 rows in the result set, we cannot imagine of iterating the variable i like that, and then make a list of integers out of it. So, I would like to know that if there are any other alternative solutions available for it whichever are efficient enough quite directly.

Upvotes: 2

Views: 14444

Answers (3)

CL.
CL.

Reputation: 180162

You do not need to call fetchall(); you can iterate directly over the cursor:

crsr.execute("SELECT ...")
for row in crsr:
    print row[0]

This will compute the result rows on demand, so the entire list never needs to be kept in memory.

And you can simplify this further: execute() returns the cursor object itself, and you can use tuple assignment to extract the value(s) from the row:

for (board,) in crsr.execute("SELECT board FROM ..."):
    print board

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599778

There's almost never a good reason to iterate over range(len(something)). Always iterate over the thing itself.

[row[0] for row in result]

Upvotes: 1

Colin Ricardo
Colin Ricardo

Reputation: 17259

You can use the row_factory attribute like this:

connection = sqlite3.connect("spline.db")
conn.row_factory = lambda cursor, row: row[0]
crsr = connection.cursor()
crsr.execute("SELECT board FROM positions WHERE balls = 1")
result = crsr.fetchall()
print result
connection.close()

This should give you a list, instead of tuples.

You can read more about row_factory here.

Upvotes: 7

Related Questions