如何使用Python/SQLite获取查询结果?

4
我正在使用Python/SQLite访问数据库。在运行查询并获取结果后,我想知道查询结果和数据库中的行数、列数和列名。
例如,如果我运行“SELECT * from table”,并获得以下结果:
id name number -------------------- 1 John 10 2 Jay 20
我可以知道我有2行,3列,列数为id/name/number吗?

添加

根据Rafael SDM Sierra的答案,我可以按如下方式获取信息。
    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

你是否正在使用Python ORM?像Django或SQLAlchemy这样的工具都有API可以帮助你获取所需的信息。 - rubayeet
@rubayeet:不,我只是使用Python/SQLite,代码中的导入语句为'from sqlite3 import dbapi2 as sqlite3'。 - prosseek
2个回答

3

Python中的SQLite3不支持.rowcount属性,并且始终返回-1。

但是,如果想要知道可以使用哪些列,则可以使用.description属性。

>>> 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))
>>> 

关于.description属性的更多信息,请查看这里:http://www.python.org/dev/peps/pep-0249/


2

因为 cursor.rowcount 不起作用,所以您需要获取计数并提取数字,使用以下代码:

result = cursor.execute('select count(*) from the_table') print "rowcount = ",result.fetchone()[0]请注意保留 HTML 标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接