Sqlite正确提交可能的崩溃方法

时间:2017-08-27 03:39:35

标签: python python-3.x sqlite

Python 3.5。 sqlite3的

目标是有一个方法将记录添加到日志表中,但它不知道该方法是否会崩溃:

  1. 打开记录器连接
  2. 记录器插入"方法启动"
  3. 做点什么
  4. 记录器插入"我做了一些事情"
  5. 做另一件事
  6. 记录器插入"我做了另一件事"
  7. 记录器插入"方法结束"
  8. 关闭记录器连接
  9. 我该怎么做?

    直到现在,在学习Sqlite时我虽然必须使用尽可能多的execute,但在关闭实际连接之前只需提交它们,然后保存"变化,如下所示:

    conn = sqlite3.connect("myfile.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO foo VALUES (?,?)", (var1, var2))
    cursor.execute("INSERT INTO other VALUES (?,?)", (var1, var2))
    cursor.execute("INSERT INTO another VALUES (?,?)", (var1, var2))
    conexion.commit() # Save all
    cursor.close()
    conn.close()
    

    但是如果我们考虑到之前它会崩溃它会进入提交部分,你会怎么做?为什么呢?

    供参考,这是我的真实代码:

    def connect(database):
        """Open a connection and a cursor to the database file provided."""
        conexion = sqlite3.connect(database + ".db")
        cursor = conexion.cursor()
        return (conexion, cursor)
    
    def disconnect(conexion, cursor, savechanges=False):
        """Disconnect from database, closing the cursor first.
        Save the cursor data with a commit if specified.
        """
        cursor.close()
        if savechanges:
            conexion.commit()
        conexion.close()
    
    def logger_query(cursor, comments):
        """It inserts into the log database an unique record with comments"""
        record_date = str(datetime.datetime.now())
        cursor.execute("INSERT INTO Log VALUES (?,?)", (comments, record_date))
    

    称为:

    conexionlog, cursorlog = connect("Log")
    logger_query(cursorlog, "Record starts")
    #... Do something
    logger_query(cursorlog, "Record something")
    #... Do another something
    logger_query(cursorlog, "Record another something")
    #... Maybe I crash here...
    logger_query(cursorlog, "Record ends")
    disconnect(conexionlog, cursorlog, True)
    

1 个答案:

答案 0 :(得分:1)

根据评论澄清更新:

根据您的评论,您不是指例外,而是实际的硬终止(例如电源故障)。在这种情况下,您需要单独提交日志查询,因为已提交的事务是唯一通过这样的硬终止持久存储的事务。

def logger_query(cursor, comments):
    """It inserts into the log database an unique record with comments"""
    record_date = str(datetime.datetime.now())
    cursor.execute("INSERT INTO Log VALUES (?,?)", (comments, record_date))
    cursor.connection.commit()

上一个答案:

假设crash表示异常被引发,您可以使用try/finally块:

conexionlog, cursorlog = connect("Log")
try:
    logger_query(cursorlog, "Record starts")
    #... Do something
    logger_query(cursorlog, "Record something")
    #... Do another something
    logger_query(cursorlog, "Record another something")
    #... Maybe I crash here...
    logger_query(cursorlog, "Record ends")
finally:
    disconnect(conexionlog, cursorlog, True)

即使finally块中的代码引发异常,也会运行try块中的代码。但请注意,只会运行已经由异常点运行的try块中的代码; try块的其余部分将不会被运行(执行将直接移动到finally块,然后是异常继续升高堆栈。)