Python SQLite3命令不会在Python中执行,但也不会导致报告的错误

csbfibhn  于 2023-01-21  发布在  SQLite
关注(0)|答案(1)|浏览(142)

我希望表最多有三行,因此一旦表有了3行,它就应该删除最旧的一行(rowid1),然后添加新的表。在表还不存在或未达到3行的情况下,它将正常地创建记录。2除了删除第一行之外,一切正常。虽然也没有错误反馈,并且当在DB浏览器中执行命令“execute 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'是一个在表中创建新记录的函数。

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

结果都一样。

yqyhoc1h

yqyhoc1h1#

我喜欢@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()

输出将如下所示:

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:

相关问题