确保在数据库中插入和更新行

时间:2014-06-11 18:04:43

标签: c# sql sql-server console-application sqlcommand

对你来说有点伪代码,系统本身更冗长:

using (var insertCmd = new SqlCommand("insert new row in database, selects the ID that was inserted", conn)) {
    using (var updateCmd = new SqlCommand("update the row with @data1 where id = @idOfInsert", conn)) {
        // Got a whole lot of inserts AND updates to process - those two has to be seperated in this system
        // I have to make sure all the data that has been readied earlier in the system are inserted

        // My MS sql server is known to throw timeout errors, no matter how long the SqlCommand.CommandTimeout is.
        for (int i = 0; i < 100000; i++) {
            if (i % 100 == 99) { // every 100th items
                // sleep for 10 seconds, so the sql server isn't locked while I do my work
                System.Threading.Thread.Sleep(1000 * 10); 
            }
            var id = insertCmd.ExecuteScalar().ToString();

            updateCmd.Parameters.AddWithValue("@data1", i);
            updateCmd.Parameters.AddWithValue("@idOfInsert", id);

            updateCmd.ExecuteNonQuery();
        }
    }
}

我如何确保ExecuteScalar和ExecuteNonQuery能够从异常中恢复?我曾经想过使用(我非常抱歉)流控制的goto和例外,例如:

Restart:
    try {
        updateCmd.ExecuteNonQuery();
    } catch (SqlException) {
        System.Threading.Thread.Sleep(1000 * 10); // sleep for 10 seconds
        goto Restart;
    }

还有另外一种方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用循环代替goto。

while(sqlQueryHasNotSucceeded)
{
    try
    {
        updateCmd.ExecuteNonQuery();
        sqlQueryHasNotSucceeded = false;
    }
    catch(Exception e)
    {
        LogError(e);
        System.Threading.Thread.Sleep(1000 * 10);
    }
}