如果超时失败,C# 重试 Sql 查询

标签 c# sql-server

有时我的查询超时并导致失败。重试执行查询的最佳方法是什么?

我在执行查询之前验证连接是否打开。但是,由于任何给定时间的服务器负载,可能需要 <1 分钟到 5 分钟以上的时间。我考虑过延长 CommandTimeout,但我认为这不是真正可行的方法。

这是我的sql查询代码。感谢您提供的所有帮助。

    private static void ExecuteQuery(string connectionString, string query)
    {
        SqlConnection connection = new SqlConnection(connectionString);
        DataTable output = new DataTable();

        try
        {
            //create new SqlAdataAdapter
            SqlDataAdapter command = new SqlDataAdapter {SelectCommand = new SqlCommand(query, connection)};

            //connect to Sqldb
            connection.Open();

            //validate connection to database before executing query
            if (connection.State != ConnectionState.Open) return;
            Console.WriteLine("Connection successful\nExecuting query...");

            //set connection timeout
            command.SelectCommand.CommandTimeout = 200;

            //create new dataSet in order to input output of query to
            DataSet dataSet = new DataSet();

            //fill the dataSet
            command.Fill(dataSet, "capacity");
            DataTable dtTable1 = dataSet.Tables["capacity"];

            Console.WriteLine("There are " + dtTable1.Rows.Count + " clusters within the capacity anlaysis.");

            output = dtTable1;
        }
        catch (Exception e)
        {
            Console.WriteLine("Unable to execute capacity (all records) query due to {0}", e.Message);
        }
        finally
        {
            connection.Close();

            Declarations.NumOfClusters = output.Rows.Count;
            Declarations.finalIssues = Issues(output, 2m, 20, true);

            Console.WriteLine("\n---------------Successfully Created Capacity DataSet---------------\n");
        }
    }

最佳答案

使用 Palmer 库:https://github.com/mitchdenny/palmer

  Retry.On<Exception>().For(TimeSpan.FromSeconds(15)).With(context =>
  {
    // Code that might periodically fail due to some issues.
       ExecuteQuery(string connectionString, string query)
       if (contect.DidExceptionLastTime)
           Thread.Sleep(200); // what ever you wish
   });

引用github页面上的API。例如,您可以检查异常的上下文,并在确实发生异常时决定休眠一段时间。 您可以重试更具体的异常。 你可以永远尝试等等。

关于如果超时失败,C# 重试 Sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733221/

相关文章:

c# - 在 EF lambda 表达式中使用扩展方法或函数

sql - 将表变量插入到具有多列(ID、数字等)的临时表中

c# - 插入记录时 Informix "no such DBspace"错误

c# - 如何增加 ASMX Web 服务的 POST 大小?

sql-server - 撤消表分区

sql - 无法在对象资源管理器中查看创建的表 - Microsoft SQL Management Studio

c# - Linq 中字符(字符串)编码的数字与数字的比较

sql - 如何阻止 SQL Server 中的 real-to-varchar(50) 转换截断值?

c# - asp.NET 4.0 + CSS 问题 : How to create a give a different effect for the current webpage on the menu?

c# - json 需要一个属性 "@class"。如何在c#中定义