Python Sqlite3数据库锁定,QWidg

2024-10-01 17:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图从pyqt小部件更新数据库时,我得到一个sqlite3.OperationalError: database is locked。在

主窗口显示数据库中的项目列表。 当双击一个项目时,一个小部件将弹出,其中包含修改数据库同一行中的值的选项。在

我有4个单独的.py文件; 我删除了大部分代码)

包含与数据库交互的所有函数的DBmanager.py。在

class DatabaseUtility:
        def __init__(self, databaseFile):
        self.db = databaseFile 
        self.conn = sqlite3.connect(self.db)
        self.c = self.conn.cursor()  

    def ChangeItemQuantity(self, itemName, incramentQuantity):
        try:
            # Change given item quantity in database
            self.c.execute('''
                 SELECT quantity
                 FROM items
                 WHERE itemName=?
                 ''',(itemName,))
            print(itemName)
            print(incramentQuantity)
            current_quantity = self.c.fetchone()
            print(current_quantity[0])
            new_quantity = current_quantity[0] + incramentQuantity
            self.c.execute('''
                 UPDATE items
                 SET quantity = ?
                 WHERE itemName=?
                 ''',(new_quantity, itemName))
            self.conn.commit()
        except Exception as error:
            # Rollback any changes if something goes wrong.
            self.conn.rollback()
            raise error

    def __del__(self):
        """Commit and close database connection when the class is terminated."""
        # pass
        self.conn.commit()
        self.c.close()
        self.conn.close()

包含GUI函数的StartGui.py。在

^{pr2}$

Mainwindow.py是从pyqt designer导出的主窗口。在

Itemwidget.py也是从pyqt designer导出的项目小部件。在

谢谢你的帮助。在


Tags: 项目pyself数据库close部件defcurrent
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:13

sqlite3文档说明:

When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed.

由于您有两个连接,一个由MainWindow打开,另一个由ItemWidget打开,因此问题的一个可能原因就是医生所说的。当另一个连接所做的更改未提交时,一个连接尝试更新数据库。这不会发生在您显示的ChangeItemQuantity方法中,因为它所做的更改是立即提交的,但是显然{}还有其他方法没有显示,比如{}。如果他们所做的更改没有立即提交,那可能就是问题所在。在

MainWindowItemWidget共享一个连接,看看问题是否解决了。您可以通过使conn成为DatabaseUtility实例的共享属性来完成此操作,而不更改调用方:

class DatabaseUtility:

    conn = None

    def __init__(self, databaseFile):
        self.db = databaseFile
        if self.__class__.conn is None:
            self.__class__.conn = sqlite3.connect(self.db)
        self.c = self.conn.cursor()

另外,尽管这看起来不太可能是问题所在,但是如果其他进程在同一个SQLite数据库上有一个打开的事务,那么只要该事务处于活动状态,该数据库就会被锁定。有些应用程序似乎有保持活动事务的坏习惯。每当我用SQLite Browser打开一个数据库时,我无法从其他程序对数据库做任何操作(也许我可以关闭它,但我从不费心去弄清楚如何…)

相关问题 更多 >

    热门问题