#update - 我修復了移動 a ) 的語法錯誤,但它仍然無法按預期作業。現在即使有重復,它也會運行回圈,這不是本意。
我正在嘗試將引號串列添加到資料庫中,但前提是作者尚不存在。我在這里遇到語法錯誤,并且沒有現有的帖子我可以找到有關此問題的幫助。將不勝感激任何幫助,并希望這對其他人有所幫助。
SELECT EXISTS 查詢的第一行給了我錯誤,但不確定這是否是最好的方法。如果我犯了一些愚蠢的新手錯誤,我希望它可以幫助其他人避免這種浪費時間的兔子洞。
#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.")
uj5u.com熱心網友回復:
您fetchone()將始終回傳一行。該行將包含 的值EXISTS,如果參考存在,則為 1,如果不存在,則為 0。因此,僅檢查是否fetchone()回傳任何內容不會告訴您是否已經存在重復項。該if條件將始終成功,您將進入回圈。
您應該檢查回傳的元組的內容fetchone():
if cursor.execute("SELECT EXISTS (SELECT 1 FROM quotebot WHERE author_name=?)", (author,)).fetchone()[0]:
或洗掉EXISTS測驗并回傳行本身:
if cursor.execute("SELECT 1 FROM quotebot WHERE author_name=? LIMIT 1", (author,)).fetchone():
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468972.html
