Python 3.5。 sqlite3的
目标是有一个方法将记录添加到日志表中,但它不知道该方法是否会崩溃:
我该怎么做?
直到现在,在学习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)
答案 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
块,然后是异常继续升高堆栈。)