Rather than having your program clean up after itself, how about have the database clean up after your program. Transactions are your friend. If you don't COMMIT your data, then when your connection to the db goes away, the changes should be thrown away.