【问题标题】:How to get queried results with Python/SQLite?如何使用 Python/SQLite 获取查询结果?
【发布时间】:2011-04-10 21:16:49
【问题描述】:

我正在使用 Python/SQLite 访问数据库。运行查询并获得结果后,我想知道查询结果和数据库中的行数、列数和列名。

例如,如果我运行“SELECT * from table”,我得到

身份证号码 -------------------- 约翰一书 10 2 周杰伦 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 :不,我只是使用 python/SQLite 作为 'from sqlite3 import dbapi2 as sqlite3'

标签: sqlite


【解决方案1】:

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]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多