0

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?

iacob
  • 20,084
  • 6
  • 92
  • 119
CrPbI3yH
  • 13
  • 4
  • 3
    `print(res[0])` what you're seeing is a `tuple` returned and not a `list` – EdChum May 31 '18 at 14:30
  • @EdChum, thank you, I'll correct the theme – CrPbI3yH May 31 '18 at 14:32
  • 2
    Alternatively, if you want to avoid having a tuple in the first place, you can unpack it on assignment with `res, = db.query("...")` (note the comma after `res`). – jdehesa May 31 '18 at 14:32
  • @jdehesa yes, it works, but how? can you explain or just give a link? Thank you, I'm really appreciate your help! – CrPbI3yH May 31 '18 at 14:34
  • one more. how can i mark it as solved? ) – CrPbI3yH May 31 '18 at 14:35
  • Here is a related question [matplotlib 2d line line,=plot comma meaning](https://stackoverflow.com/q/16742765/1782792), and [here](http://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/) there are more details and examples about tuple unpacking (single item tuple example near the end). You can just close the question since there is no actual answer posted and there are already similar questions covering the topic. – jdehesa May 31 '18 at 14:42

1 Answers1

1

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
iacob
  • 20,084
  • 6
  • 92
  • 119