LaughU
LaughU

Reputation: 253

Retrieving all records in a row in postgres with pyqt

I am writing a tool to generate reports with the help of PostgreSQL and PyQt4.

I write a query to my database like this:

 sql = "SELECT field1, field2, field3 FROM my_table ORDER BY id ASC"
 query = QSqlQuery(self.db) # self.db holds my connection to the database
 query.exec_(sql)

This works fine I can now get the values from the query like this:

 while query.next():
    print query.record().value("field1")

The next step would be storing the results in a container (list/ dictionary) and do the calculations for the report. However, in my case, I have many fields which I would need to store and calling all one by one seems a long detour.

By reading about the QSqlquery and QSqlResult did not bring any light. I tried with query.result().boundValues() but only got empty lists as return.

My expected result would be a list which holds all the values for a row.

Question: This there a way to retrieve all data in a row from a query with PyQt?

Upvotes: 1

Views: 1035

Answers (2)

Fernando Bautista
Fernando Bautista

Reputation: 9

sql=("select count(id) as total_user from datos")
query.exec_(sql)

query.next()
user=query.record().value("total_user")
self.lbl_user.setText(str(user))

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120598

The columns in the select statement are numbered from left to right (starting from zero), so you can do:

indexes = range(num_cols)
while query.next():
    row = [query.value(index) for index in indexes]

Upvotes: 3

Related Questions