-->

How to get queried results with Python/SQLite?

2019-04-13 06:49发布

问题:

I'm using Python/SQLite for accessing database. After running the query, and getting the result, I want to know the number of rows, the number of columns, and the name of the column from the queried result and database.

For example if I run "SELECT * from table", and I get

id    name    number
--------------------
1     John    10
2     Jay     20

I can I know that I have 2 rows, and 3 columns, and the number of columns are id/name/number?

ADDED

Based on Rafael SDM Sierra's answer, I could get the info as follows.

    description = self.cursor.description
    qr.numberOfCol = len(description) <-- # of column
    for item in description:
        qr.names.append(item[0]) <-- Names of column

    count = 0
    for row in self.cursor:
        count += 1
        qr.result.append(row)

    qr.numberOfRow = count <-- # of row

回答1:

SQLite3 for Python does not suport .rowcount attribute and return always -1.

But to know what are the columns you can use .description attribute.

>>> import sqlite3
>>> c = sqlite3.connect(':memory:')
>>> c.execute('CREATE table foo (bar int, baz int)')
<sqlite3.Cursor object at 0xb76e49e0>
>>> c.execute('insert into foo values (1,1)')
<sqlite3.Cursor object at 0xb778c410>
>>> c.execute('insert into foo values (2,2)')
<sqlite3.Cursor object at 0xb76e4e30>
>>> c.execute('insert into foo values (3,3)')
<sqlite3.Cursor object at 0xb778c410>
>>> cursor = c.execute('select * from foo')
>>> cursor.rowcount
-1
>>> cursor.fetchone()
(1, 1)
>>> cursor.description
(('bar', None, None, None, None, None, None), ('baz', None, None, None, None, None, None))
>>> 

For more information about .description attribute, look here: http://www.python.org/dev/peps/pep-0249/



回答2:

Because cursor.rowcount does not work, you will have to get a count back and extract the number using result = cursor.execute('select count(*) from the_table') print "rowcount = ",result.fetchone()[0]