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

本文关键字:更新 插入 确保 数据库 | 更新日期: 2023-09-27 18:08:06

给你一点伪代码,系统本身要冗长得多:

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;
    }

有没有另一种方法完全做到这一点?

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

可以使用循环符代替goto。

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