0
我已經使用sqlalchemy(我的底層數據庫是PostgreSQL 8.4)編寫了以下函數。 我有以下模式:sqlalchemy錯誤地刪除行
CREATE TABLE temporary_data_key (
id SERIAL PRIMARY KEY,
key VARCHAR(36) NOT NULL
);
CREATE UNIQUE INDEX idxu_temp_data_nm ON temporary_data_key (key);
CREATE TABLE temporary_data (
key_id INTEGER REFERENCES temporary_data_key(id) ON UPDATE CASCADE ON DELETE RESTRICT NOT NULL,
id_value INTEGER CHECK (id_value > 0) NOT NULL
);
我期待的功能,清理後本身(即刪除temporary_table_key表生成的密鑰),如果出現錯誤 - 由於某種原因,該表中沒有被清除時發生異常。
下面是函數:
def storeIdsInTemporaryTable(dbinfo, id_list):
conn = dbinfo['db_connection']
metadata = dbinfo['metadata']
tableinfo = Table('temporary_data', metadata, autoload=True)
datarows = []
temp_dbinfo = {'db_connection': conn, 'table': tableinfo, 'datarows': datarows }
guid = genutils.getGUID()
sql = "INSERT INTO temporary_data_key (key) VALUES ('{0}') RETURNING id".format(guid)
key_id = executeSQLonDbConnection(temp_dbinfo, sql, return_field='id')
for id_value in id_list:
datarows.append({ 'key_id': key_id, 'id_value': id_value })
try:
insertToDb(temp_dbinfo)
except Exception as e:
print 'ERROR:',e
guid = None # to indicate an error occured
if key_id:
conn.execute("DELETE FROM temporary_data_key WHERE key='{0}'".format(key_id))
return guid
任何人都可以找出爲什麼功能不清理temporary_data密鑰,作爲例外處理部分?