gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:46:19 24 4
gpt4 key购买 nike

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

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

id    name    number--------------------1     John    102     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

最佳答案

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/

关于sqlite - 如何使用 Python/SQLite 获取查询结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com