python sqllite 查_如何用Python检查SQLite中是否存在行?

由于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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值