简体   繁体   English

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

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

I want the table to have a maximum of three rows so once the table has 3, it should delete the oldest one (rowid 1) and then add on the new one.我希望表最多有三行,所以一旦表有 3 行,它应该删除最旧的行(rowid 1),然后添加新行。 In the case that the table doesn't exist yet or hasn't reached 3 rows, it will just create the record normally.如果表还不存在或未达到 3 行,它将正常创建记录。 Everything works except for deleting the first row.除了删除第一行外,一切正常。 Although there is no error feedback either and when the command is executed in the DB browser 'execute SQL' it works perfectly, it just doesn't work when run from my IDE. The new record is made but on top of the three already there instead of being added as the third after the first is deleted.尽管也没有错误反馈,并且当在数据库浏览器中执行命令“执行 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()

Note that the connection to the database is established before this code and 'CreateNew' is a function that creates the new record in the table.请注意,在此代码之前建立了与数据库的连接,并且“CreateNew”是在表中创建新记录的 function。 Additionally, I have tried:另外,我试过:

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

Only to have the same result.只是为了得到相同的结果。

I like the idea from @jarh to use a trigger in sqlite3 : Here is a small mockup:我喜欢@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() 

The output will be like: 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