栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Python检查SQLite中是否存在行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Python检查SQLite中是否存在行?

由于

name
s是唯一的,因此与我最初使用的建议相比,我真的更喜欢您(OP的)使用方法
fetchone
或Alex
Martelli的使用方法。
SELECt count(*)``fetchall

fetchall
将结果(通常是多行数据)包装在一个列表中。由于
name
s是唯一的,因此
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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624690.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号