簡體   English   中英

Python SQLite3 命令不會在 python 中執行,但也不會導致報告錯誤

[英]Python SQLite3 command won't execute in python but also causes no reported errors

我希望表最多有三行,所以一旦表有 3 行,它應該刪除最舊的行(rowid 1),然后添加新行。 如果表還不存在或未達到 3 行,它將正常創建記錄。 除了刪除第一行外,一切正常。 盡管也沒有錯誤反饋,並且當在數據庫瀏覽器中執行命令“執行 SQL”時它運行良好,但從我的 IDE 運行時它就不起作用了。新記錄已創建,但在已有的三個記錄之上而不是在刪除第一個后添加為第三個。

 cursor.execute("SELECT count(*) from TableOne")
 searchResults = cursor.fetchone()
 NoOfRows=searchResults[0]
 if NoOfRows ==3:
     cursor.execute("DELETE FROM TableOne WHERE rowid=1")
     connection.close()
     CreateNew()
 else:   
     CreateNew()

請注意,在此代碼之前建立了與數據庫的連接,並且“CreateNew”是在表中創建新記錄的 function。 另外,我試過:

Num=1
cursor.execute("DELETE FROM TableOne WHERE rowid=?",[Num])

只是為了得到相同的結果。

我喜歡@jarh在 sqlite3 中使用觸發器的想法:這是一個小模型:

import sqlite3
    
sql1 = """CREATE TABLE IF NOT EXISTS table_one (
        id integer PRIMARY KEY,
        name text NOT NULL
        );"""

################## TRIGGER START ####################
sqlt = """CREATE TRIGGER IF NOT EXISTS rem_col_one
        BEFORE INSERT ON table_one
        WHEN (SELECT count(*) FROM table_one WHERE rowid > 2) 
        BEGIN
            DELETE FROM table_one WHERE rowid = last_insert_rowid()-2;
        END
        """
################## TRIGGER  END #####################

  
def db_insert(cur, name):
    sql2 = """INSERT INTO table_one (name) VALUES(?);"""
    sql3 = """SELECT * FROM table_one"""
    cur.execute(sql2,(name,))
    cur.execute(sql3)
    print(cur.fetchall())
     
def main():
    con = sqlite3.connect('Test.db')
    cur = con.cursor()
    cur.execute(sql1)
    cur.execute(sqlt)
    
    value_db = None
    while value_db != 'quit':
        value_db = input(f"Enter the next Name [or 'quit']: ")
        if value_db != 'quit':
            db_insert(cur, value_db) 
            con.commit()
    con.close()

if __name__ == "__main__":
    main() 

output 將類似於:

Enter the next Name: Hugo
[(1, 'Hugo')]
Enter the next Name: Max
[(1, 'Hugo'), (2, 'Max')]
Enter the next Name: Moritz
[(1, 'Hugo'), (2, 'Max'), (3, 'Moritz')]
Enter the next Name: Dilbert
[(2, 'Max'), (3, 'Moritz'), (4, 'Dilbert')]
Enter the next Name: Dagobert
[(3, 'Moritz'), (4, 'Dilbert'), (5, 'Dagobert')]
Enter the next Name: 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM