由于
names是唯一的,因此与我最初使用的建议相比,我真的更喜欢您(OP的)使用方法
fetchone或Alex
Martelli的使用方法。
SELECt count(*)``fetchall
fetchall将结果(通常是多行数据)包装在一个列表中。由于
names是唯一的,因此
fetchall返回列表中只有一个元组的列表(例如,
[(rowid,),]或为空列表
[]。如果您想知道
rowid,则使用
fetchall要求您浏览列表和元组以到达
rowid。
fetchone在这种情况下使用更好,因为您只会得到一行
(rowid,)或
None。要获得
rowid(假设有一个),您只需选择元组的第一个元素。
如果您不在乎特定内容,
rowid而只是想知道是否有点击,则可以使用Alex Martelli的建议
SELECTcount(*),该建议将返回
(1,)或
(0,)。
这是一些示例代码:
首先,通过一些样板代码来设置玩具方桌:
import sqlite3connection = 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 barComponent 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 barComponent 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 barComponent foo found in 1 row(s)



