【问题标题】:Python SQLite3 command won't execute in python but also causes no reported errorsPython SQLite3 命令不会在 python 中执行,但也不会导致报告错误
【发布时间】:2023-01-20 06:55:33
【问题描述】:

我希望表最多有三行,所以一旦表有 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”是在表中创建新记录的函数。另外,我试过:

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

只是为了得到相同的结果。

【问题讨论】:

  • 这回答了你的问题了吗? SQLite delete query not working?
  • 我会考虑基于触发器的解决方案。
  • @jarlh 他们不只是缺少commit()吗?
  • @JonSG,也许吧。即使其他人插入值(不记得 3 行规则的人),基于触发器的解决方案也会起作用。

标签: python sql database sqlite sqlite3-python


【解决方案1】:

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

sql2 = """INSERT INTO table_one (name) VALUES(?);"""

sql3 = """SELECT * FROM table_one"""
  
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)
    
    while True:
        value_db = input('Enter the next Name: ')
        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: 

【讨论】:

    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2020-07-05
    • 2021-07-17
    相关资源
    最近更新 更多