如何判断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()
如果email
和username
不在数据库中,我希望它只将值插入数据库,但我不知道从哪里开始。
答案 0 :(得分:3)
您需要做的就是在插入之前进行查询,并执行fetchone
。如果fetchone
返回了某些内容,那么您肯定知道数据库中已存在email
或username
的记录:
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()