简体   繁体   English

检查条目存在于 sqlite3 python 中

[英]Check entry exists in sqlite3 python

I checked some similar posts, but don't get my answer.我查了一些类似的帖子,但没有得到我的答案。

I want to check if specific username is in database or not.我想检查特定的用户名是否在数据库中。

import sqlite3
con = sqlite3.connect("session.db")
c = con.cursor()
a1 = 'jack'
c.execute("SELECT EXISTS(SELECT username FROM User WHERE username=?)", (a1))
if c.fetchone():
    print("Found!")

else:
    print("Not found...")

在此处输入图片说明

Your script has one obvious problem with it, namely that you are not actually passing a valid Python tuple to the call to execute() .您的脚本有一个明显的问题,即您实际上并未将有效的 Python 元组传递给对execute()的调用。 Instead, you are passing a single string variable.相反,您传递的是单个字符串变量。 You should be passing (a,) , with a trailing comma, to tell Python that you intend this to mean a tuple.您应该传递(a,) ,并带有一个尾随逗号,以告诉 Python 您打算这是一个元组。

import sqlite3
con = sqlite3.connect("session.db")
c = con.cursor()
a1 = 'jack'
c.execute("SELECT EXISTS (SELECT 1 FROM User WHERE username = ?)", (a1,))
if c.fetchone():
    print("Found!")
else:
    print("Not found...")

To be clear here, ('jack') will be interpreted as a string, while ('jack',) will be interpreted as a tuple.在这里要清楚, ('jack')将被解释为一个字符串,而('jack',)将被解释为一个元组。

You should change your code a bit like this-你应该像这样改变你的代码 -

c.execute("SELECT EXISTS(SELECT username FROM User WHERE username=?)", (a1,))

Notice the comma after a1 .注意a1后面的逗号。 Without this change the code should throw an error like Incorrect number of bindings supplied as only a1 (in your case value jack ) will be treated as 4 different parameter provided to c.execute() .如果没有此更改,代码应该会抛出错误,例如Incorrect number of bindings supplied c.execute() as only a1 (在您的情况下值为jack )将被视为提供给c.execute() 4 个不同参数。 Turning it to tuple will bind the whole string jack to the appropriate placeholder.将其转换为元组会将整个字符串jack绑定到适当的占位符。

After that check the result like -之后检查结果,如 -

found, = c.fetchone()
# found will be 1 in case the entry is present
if found: 
    print("Found")
else:
    print("Not found")

c.fetchone() returns a tuple. c.fetchone()返回一个元组。 In your case tuple with one element indicating whether the entry exists or not (1 if present, 0 otherwise)在您的情况下,元组有一个元素指示该条目是否存在(如果存在,则为 1,否则为 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM