I am using a Sql transaction in a program to ensure that if the program crashes half way through a set of queries, it gets rolled back, but I'mthinking maybe transactions don't do what I think they do. Here is example code:
This basically performs some queries on 4 identical tables so it just loops through. Idealy if the program crashes for any reason in the middle of that loop, I want to make sure none of the changes actually take effect. However, when I run this code, with the purposeful crash after the first loop, the queries end up having been committed to the first table.
Is this normal behavior when dealing with transactions, or is there something wrong?
Suppose worse case scenario I can set a flag somewhere when it starts, and then set it back off when it ends, and then when the program loads if the flag is set it means it did not save correctly and it would either raise a warning, or simply halt startup requiring to restore from backup. 99% of the time this won't cause an issue though, so maybe I should just leave it alone, but ideally it's always better safe than sorry I suppose.
Code:
private static bool SqlSnapshot()
{
bool res=true;
m_connector.Query("START TRANSACTION;");
for(int i=0;i<SerializeObjectTableNum;i++)
{
//delete anything with pending status 2:
res = m_connector.Query(String.Format("DELETE FROM serializeobjects{0} WHERE o_pendingstatus=2;",i));
if(!res)break;
//update anything with pending status 1
res = m_connector.Query(String.Format("UPDATE serializeobjects{0} set o_data=o_newdata, o_newdata='', o_pendingstatus='0' WHERE o_pendingstatus=1;",i));
if(!res)break;
//debug - test crash!
int a = 0;
int b = 5/a;
}
if(!res)m_connector.Query("ROLLBACK;");
else m_connector.Query("COMMIT;");
return res;
}
This basically performs some queries on 4 identical tables so it just loops through. Idealy if the program crashes for any reason in the middle of that loop, I want to make sure none of the changes actually take effect. However, when I run this code, with the purposeful crash after the first loop, the queries end up having been committed to the first table.
Is this normal behavior when dealing with transactions, or is there something wrong?
Suppose worse case scenario I can set a flag somewhere when it starts, and then set it back off when it ends, and then when the program loads if the flag is set it means it did not save correctly and it would either raise a warning, or simply halt startup requiring to restore from backup. 99% of the time this won't cause an issue though, so maybe I should just leave it alone, but ideally it's always better safe than sorry I suppose.