繁体   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