我试图在下面的函数中使用finally,但是,Python报告了一个语法错误。我确定我做的很傻,但我似乎无法发现它......
代码段如下:
# Store ids with key
# Returns GUID (used to clear table after words)
def storeIdsInTemporaryTable(dbinfo, id_list):
conn = dbinfo['db_connection']
guid = genutils.getGUID()
orig_tableinfo = dbinfo['table']
orig_datarows = dbinfo['datarows']
metadata = dbinfo['metadata']
sql = "INSERT INTO temporary_data_key (key) VALUES ({0}) RETURNING id".format(guid)
key_id = executeSQLonDbConnection(dbinfo, sql, return_field='id')
tableinfo = Table('temporary_data', metadata, autoload=True)
datarows = []
for id_value in id_list:
datarows.append( { 'key_id': key_id, 'id_value': id_value} )
try:
insertToDb(dbinfo)
except:
guid = None # to indicate an error occured
if key_id:
conn.execute("DELETE FROM temporary_data_key WHERE key={0}".format(guid)
finally:
dbinfo['table'] = orig_tableinfo
dbinfo['datarows'] = orig_datarows
return guid
导致语法错误的原因是什么?
顺便说一句,我知道我需要在事务中包装两个插入,但由于某种原因,我无法使事务工作(SQLALchemy抛出与事务相关的错误) - 所以那是另一个问题另一个时间..
[[编辑]]
异常错误(现已修复)为:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/script.py", line 1632
finally:
^
SyntaxError: invalid syntax
答案 0 :(得分:13)
您使用的是Python&lt; 2.5?尝试除了最后只在2.5中添加,然后你必须包装尝试除了最后尝试。
答案 1 :(得分:5)
您在致电execute()
时错过了一个右括号。它应该是:
conn.execute("DELETE FROM temporary_data_key WHERE key={0}".format(guid))
而不是:
conn.execute("DELETE FROM temporary_data_key WHERE key={0}".format(guid)