1

我有一个使用几个 sql 数据库来存储数据的程序。我有一个管理各种 sql 函数的类,例如获取值、整个表或仅更新值。在我运行一个使用 UPDATE 的函数之前,所有进程都可以正常工作。我执行 UPDATE 命令并尝试提交更改,并且数据库始终处于锁定状态。我的自定义 sql 类中的每个函数都有

cursor.close
database.close

因此,数据库连接仍处于打开状态应该没有任何问题。我是否在此语法中遗漏了未正确连接到数据库的内容?我使用额外的打印语句试图找出问题发生的位置,因此可以忽略这些语句。

import sqlite3 as db
import os
databaseName = "site"

class MassDb:
    def __init__(self,databaseName):
        super(MassDb, self).__init__()
        print("Current Directory: ",os.getcwd())
        self.databaseName = databaseName  

    def updateValue(self, location, metric, input_value):
        print("OPEN CONNECTION UPDATE - running updateValue: ",location, metric, input_value)
        if self.databaseName == "site": 
            try: 
                siteConn = db.connect("site_data.db")
                siteCursor = siteConn.cursor()
                siteCursor.execute("UPDATE sites SET " + metric + " = ? WHERE LOCATI    ON = ?", (input_value, location))
                siteConn.commit()
            except: 
                print("UPDATE FAILED")
            finally: 
                siteCursor.close
                siteConn.close

        elif self.databaseName == "comp": 
            try: 
                compConn = db.connect("comp_data.db")
                compCursor = compConn.cursor()
                compCursor.execute("UPDATE competitors SET " + metric + " = ? WHERE NAME = ?", (input_value, location))
                compConn.commit()
            except: 
                print("UPDATE FAILED")
            finally: 
                compCursor.close
                compConn.close
                print("CLOSED CONNECTION UPDATE - Update Connection Closed")
        else: 
            print("Update Error")

MassDb("site").updateValue("Location", "CURRENT_SCORE", "100")
4

1 回答 1

1

正如@roganjosh 评论的那样,我的问题是我没有正确关闭数据库。如果

commit() 

已使用,无需关闭数据库。然而,

cursor.close() 

conn.close() 

需要这样写。去掉括号就好像引用了一个属性,而不是一个方法。为了执行 close 方法, () 必须存在。现在似乎很明显,但我当时并不知道。希望这可以帮助其他人,如果他们也遇到这个问题。

此外,使用上下文管理器可以工作并且无需使用close()

with conn:
    #do stuff here
    commit()
于 2018-09-05T22:20:24.980 回答