gpt4 book ai didi

python - 如何判断sqlite3数据库中是否存在值,python

转载 作者:行者123 更新时间:2023-12-03 17:46:54 25 4
gpt4 key购买 nike

如何判断一个值是否存在于 sqlite3 数据库中,python

到目前为止,这是我的代码:

def signup():
email = request.form['email']
username = request.form['user']
password = request.form['password']
g.db.execute("INSERT INTO users VALUES (?, ?, ?)", [email, username, password])
g.db.commit()

如果 emailusername 不在数据库中,我希望它只将值插入数据库,但我不知道从哪里开始。

最佳答案

您所要做的就是在插入之前进行查询,然后执行 fetchone .如果 fetchone 返回一些东西,那么您肯定知道数据库中已经有一条记录,该记录具有 emailusername:

def signup():
email = request.form['email']
username = request.form['user']
password = request.form['password']

# Create cursor object
cur = g.db.cursor()

# run a select query against the table to see if any record exists
# that has the email or username
cur.execute("""SELECT email
,username
FROM users
WHERE email=?
OR username=?""",
(email, username))

# Fetch one result from the query because it
# doesn't matter how many records are returned.
# If it returns just one result, then you know
# that a record already exists in the table.
# If no results are pulled from the query, then
# fetchone will return None.
result = cur.fetchone()

if result:
# Record already exists
# Do something that tells the user that email/user handle already exists
else:
cur.execute("INSERT INTO users VALUES (?, ?, ?)", (email, username, password))
g.db.commit()

关于python - 如何判断sqlite3数据库中是否存在值,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com