【问题标题】:Connection Timeout SQL c#连接超时 SQL c#
【发布时间】:2020-07-08 01:20:42
【问题描述】:

我有一个项目,当我尝试运行它并且数据测试很大时,我总是遇到连接超时。 我添加了“sqlCmd.CommandTimeout = 3600;”但仍然无法正常工作。 我做错了什么?

这是我的代码

public void createCode(String ce, int ord, String beh, int wkd)
{
        String strSql = "";
        SqlCommand sqlCmd;

        SqlConnection conexion = new SqlConnection(getConexion());

        try
        {
            if (conexion.State != ConnectionState.Open)
                conexion.Open();

            //The insert works fine in sql server
            strSql = "Insert into x with values"; 

            sqlCmd = new SqlCommand(strSql, conexion);
            sqlCmd.CommandTimeout = 3600;
            sqlCmd.ExecuteScalar();
        }
        catch (Exception ex)
        {               
            throw new Exception("Error creating Code. " + ex.Message);
        }
        finally
        {
            if (conexion.State == ConnectionState.Open)
                conexion.Close();
        }

}

【问题讨论】:

  • 请提供错误消息和连接字符串(混淆其秘密部分)。区分两种不同的超时类型很重要:ConnectionTimeout and CommandTimeout。哪个超时会导致您的代码出错?

标签: c# sql connection-timeout


【解决方案1】:

您可能需要在配置文件中设置事务超时,如下所示;

<system.transactions>
   <defaultSettings timeout="01:00:00" />
</system.transactions>

【讨论】:

  • 非常感谢!这就是问题所在! :)
  • 很高兴为您提供帮助:)
【解决方案2】:

sqlCmd.ExecuteScalar() 对您的脚本不正确,请尝试改用 sqlCmd.ExecuteNonQuery() 并删除超时。

        sqlCmd = new SqlCommand(strSql, conexion);
        sqlCmd.ExecuteNonQuery();

检查每个函数,ExecuteScalar 尝试从选择返回第一个值,而 ExecuteNonQuery 不检索任何值,只是获取受影响的行数。

希望对你有帮助!

【讨论】:

  • 这不是问题,因为我多年来一直在使用它。但谢谢大卫。
  • 所以如果你确定你的脚本和sql没问题,你可以使用sqlCmd.CommandTimeout = 0,它不会因为sql超时而失败。
猜你喜欢
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-12
  • 2021-05-12
  • 2018-05-25
  • 1970-01-01
相关资源
最近更新 更多