SqlConnection有什么问题?

时间:2019-12-20 18:40:25

标签: c# sql .net sql-server ado.net

我有一个代码来检查具有某些指定名称的存储过程是否已经部署。代码是

protected virtual async Task<bool?> IsProcedureDeployed(string storedProcedureName)
        {
            try
            {
                SqlCommand sqlCommand = new SqlCommand
                {
                    CommandText = "select count(*) from sysobjects where type = 'P' and name = @storedProcedureName",
                    CommandType = CommandType.Text,
                    CommandTimeout = this.CommandTimeout
                };

                await this.EnsureConnectionOpened();
                int count = (int)(await sqlCommand.ExecuteScalarAsync());

                return count > 0;
            }
            catch (Exception exception)
            {
                this.SqlConnection.Close();
                ExceptionDispatchInfo.Capture(exception).Throw();
                return null;
            }
        }

this.EnsureConnectionOpened看起来像这样:

protected async Task EnsureConnectionOpened()
        {
            if (SqlConnection.State == ConnectionState.Closed && SqlTransaction == null)
            {
                await SqlConnection.OpenAsync();
            }
        }

,而在执行int count = (int)(await sqlCommand.ExecuteScalarAsync());时,它总是抛出一个异常,该异常表示...“无效的操作。连接已关闭。”。我已经检查了SqlConnection的状态,并且它是Open!我到底在做什么错了?

编辑。每个SqlCommand必须具有SqlConnection和正确设置的参数(如果需要)。最终版本是

protected virtual async Task<bool?> IsProcedureDeployed(string storedProcedureName)
        {
            try
            {
                SqlCommand sqlCommand = new SqlCommand("select count(*) from sysobjects where type = 'P' and name = @storedProcedureName", this.SqlConnection)
                {
                    CommandType = CommandType.Text,
                    CommandTimeout = this.CommandTimeout
                };

                SqlParameter sqlParameter = new SqlParameter
                {
                    ParameterName = "@storedProcedureName",
                    Value = storedProcedureName
                };

                sqlCommand.Parameters.Add(sqlParameter);

                await this.EnsureConnectionOpened();
                int count = (int)(await sqlCommand.ExecuteScalarAsync());

                return count > 0;
            }
            catch (Exception exception)
            {
                this.SqlConnection.Close();
                ExceptionDispatchInfo.Capture(exception).Throw();
                return null;
            }
        }

1 个答案:

答案 0 :(得分:2)

我会稍微修改这种方法。将所有连接内容放在同一位置,而不是分散在整个位置。另外,由于您发布的代码仅使用try / catch来关闭连接(并重新抛出异常),因此我将其完全删除。您无需在此处进行任何错误处理。让异常发生并冒泡到调用方法。我猜这种逻辑在您的数据层中?

这样的东西很整洁。

protected virtual async Task<bool?> IsProcedureDeployed(string storedProcedureName)
{
    bool IsDeployed = false;
    using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString))
    {
        conn.Open();
        using (var cmd = new SqlCommand("select count(*) from sysobjects where type = 'P' and name = @storedProcedureName", conn))
        {
            cmd.Parameters.Add("@storedProcedureName", SqlDbType.NVarChar, 128).Value = storedProcedureName; //using nvarchar(128) because object names use sysname which is a synonym for nvarchar(128)
            var result = await cmd.ExecuteScalarAsync();
            bool.TryParse(result.ToString(), out IsDeployed);
        }
    }
    return IsDeployed;
}