自从name
是独一无二的,我真的很喜欢你(OP)的使用方法fetchone
或 Alex Martelli 的使用方法SELECT count(*)
超过我最初的使用建议fetchall
.
fetchall
将结果(通常是多行数据)包装在列表中。自从name
是独一无二的,fetchall
返回列表中只有一个元组的列表(例如[(rowid,),]
或一个空列表[]
。如果您想了解rowid
,然后使用fetchall
要求您深入列表和元组才能找到rowid
.
Using fetchone
在这种情况下更好,因为你只得到一行,(rowid,)
or None
。
为了到达rowid
(前提是有一个)您只需选取元组的第一个元素即可。
如果你不关心具体的rowid
你只是想知道有热门产品,
那么你可以使用 Alex Martelli 的建议,SELECT count(*)
,这将返回(1,)
or (0,)
.
这是一些示例代码:
首先是一些用于设置玩具 SQLite 表的样板代码:
import sqlite3
connection = sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('create table components (rowid int,name varchar(50))')
cursor.execute('insert into components values(?,?)', (1,'foo',))
Using fetchall
:
for name in ('bar','foo'):
cursor.execute("SELECT rowid FROM components WHERE name = ?", (name,))
data=cursor.fetchall()
if len(data)==0:
print('There is no component named %s'%name)
else:
print('Component %s found with rowids %s'%(name,','.join(map(str, next(zip(*data))))))
yields:
There is no component named bar
Component foo found with rowids 1
Using fetchone
:
for name in ('bar','foo'):
cursor.execute("SELECT rowid FROM components WHERE name = ?", (name,))
data=cursor.fetchone()
if data is None:
print('There is no component named %s'%name)
else:
print('Component %s found with rowid %s'%(name,data[0]))
yields:
There is no component named bar
Component foo found with rowid 1
Using SELECT count(*)
:
for name in ('bar','foo'):
cursor.execute("SELECT count(*) FROM components WHERE name = ?", (name,))
data=cursor.fetchone()[0]
if data==0:
print('There is no component named %s'%name)
else:
print('Component %s found in %s row(s)'%(name,data))
yields:
There is no component named bar
Component foo found in 1 row(s)