CrPbI3yH
CrPbI3yH

Reputation: 13

Python to convert tuple to value

I'm trying to retrive number of rows in table with:

import postgresql

db = postgresql.open(...)
res = db.query("select count(1) from testdata")
print(res)
>>> (10,)

How can I print just 10?

Upvotes: 0

Views: 283

Answers (1)

iacob
iacob

Reputation: 24231

db.query() returns a tuple of query results, even if the query seeks only one value. We can iterate through the response's results using the next method:

import postgresql

db = postgresql.open(...)
res = db.query("select count(1) from testdata")
count_result = res.next()

(see Data Wrangling with Python p.212).


Alternative approaches:

count_result = res[0] # first argument of res is the count
count_result, *_ = db.query("select count(1) from testdata") 
# first argument assigned to `count_result`
# subsequent arguments unassigned

Upvotes: 1

Related Questions