由于name是唯一的,我真的很喜欢你使用fetchone或亚历克斯·马泰利使用SELECT count(*)的方法,而不是我最初建议的使用fetchall。
fetchall将结果(通常是多行数据)包装在一个列表中。由于name是唯一的,fetchall返回列表中只有一个元组的列表(例如[(rowid,),])或空列表[]。如果您想知道rowid,那么使用fetchall需要您在列表和元组中钻研以获得rowid。
在这种情况下,使用fetchone更好,因为您只得到一行,(rowid,)或None。
要获得rowid(只要有一个),只需选取元组的第一个元素。
如果你不在乎某个特定的rowid而你只想知道有一个点击,
然后可以使用Alex Martelli的建议SELECT count(*),它将返回(1,)或(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',))
使用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))))))
收益率:There is no component named bar
Component foo found with rowids 1
使用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]))
收益率:There is no component named bar
Component foo found with rowid 1
使用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))
收益率:There is no component named bar
Component foo found in 1 row(s)