[PyQt] Extracting QSqlQuery results in PyQt4

Mark Summerfield mark at qtrac.eu
Thu Oct 9 08:24:32 BST 2008


On 2008-10-08, mir amicitas wrote:
> I am trying to use SQLite in a PyQt4 application. I am running into a
> problem where it is taking a really long time to get the data out of
> the QSqlQuery object after a query is completed. Here is a code
> snippet with the relevant parts:
>
> #################################################################
>         self.selected_columns = self.table_definition['track']
>         select_string = ','.join(self.selected_columns)
>
>         query_str = 'SELECT %s FROM track %s'%(select_string, where_string)
>
>         start_time = time.clock()
>         self.query.prepare(query_str)
>         self.query.exec_()
>         util.message('Query took:', time.clock() - start_time, 'seconds')
>
>         print ''
>         print query_str
>
>         results = []
>         header = self.selected_columns
>
>         self.query.first()
>
>         while self.query.isValid():
>             record = [self.query.value(index).toString() for index in
> range(len(header))]
>             results.append(record)
>             self.query.next()
>
>         util.message('Selected', len(results), 'records.')
>
>         util.message('Unpacking Took:', time.clock() - start_time,
> 'seconds')

I think someone has already given some suggestions regarding speed, so
here is one on style:

Instead of calling query.first() and query.isValid() just do:

    while query.next():
	...

The first time query.next() is called it will go to the first record;
and when there are no more records it will return False.

[snip]

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "C++ GUI Programming with Qt 4" - ISBN 0132354160




More information about the PyQt mailing list