如果数据库中不存在值,则运行循环
#update-我修复了移动a)的语法错误,但它仍然无法按预期工作。现在,它即使以重复的方式运行循环,这不是意图。
我正在尝试将报价列表添加到数据库中,但前提是作者不存在。我在这里遇到语法错误,没有现有的帖子,我可以在此问题上找到帮助。感谢任何帮助,并希望这对他人有所帮助。
存在选择的第一行是查询会给我带来错误,但不确定这是否是这样做的最佳方法。如果我犯了一些新手错误,我希望它可以帮助别人避免将来浪费时间的兔子洞。
#Check if author already exists
if cursor.execute("SELECT EXISTS (SELECT 1 FROM quotebot WHERE author_name=?)", (author,)).fetchone():
for text, author, title, in all_quotes:
try:
if text is None or title is None and text == "":
continue
# Insert quote into table
cursor.execute("INSERT INTO quotebot("long-query-that-works"))
sqliteConnection.commit()
print('Quote Successfully Added')
# Handle errors
except sqlite3.Error as error:
print('Error occured - ', error)
else:
print("This author is already in the database. Please try a new author.")
#update - I fixed the syntax error moving a ), but it still doesn't work as intended. Now it runs the loop even with a duplicate, which is not the intent.
I'm trying to add a list of quotes to a database, but only if the author doesn't already exist. I'm getting a syntax error here, and no existing posts I could find help with this issue. Would appreciate any help, and hope this helps others.
The first line with the SELECT EXISTS query gives me the error, but not sure if this is the best way to do this anyway. If I made some boneheaded newbie error, I hope it helps someone else avoid this rabbit hole of time wasting in the future.
#Check if author already exists
if cursor.execute("SELECT EXISTS (SELECT 1 FROM quotebot WHERE author_name=?)", (author,)).fetchone():
for text, author, title, in all_quotes:
try:
if text is None or title is None and text == "":
continue
# Insert quote into table
cursor.execute("INSERT INTO quotebot("long-query-that-works"))
sqliteConnection.commit()
print('Quote Successfully Added')
# Handle errors
except sqlite3.Error as error:
print('Error occured - ', error)
else:
print("This author is already in the database. Please try a new author.")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
fetchone()
将始终返回一行。该行将包含存在的值
,如果存在引用,则为1,如果不存在,则为0。因此,只需检查fetchone()
返回任何内容都不会告诉您是否已经重复。如果条件将始终成功,并且您将进入循环。您应该检查由
fetchone()
返回的元组内容:或删除已存在的,测试并返回行本身:
Your
fetchone()
will always return a row. The row will contain the value ofEXISTS
, either 1 if the quote exists or 0 if it doesn't. So just checking whetherfetchone()
returns anything will not tell you if there's already a duplicate. Theif
condition will always succeed and you'll go into the loop.You should check the contents of the tuple returned by
fetchone()
:or remove the
EXISTS
test and return the row itself: