方法更新C#连接错误

时间:2017-07-27 21:36:06

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

我创建了一个名为update的方法来更新数据库中的数据,该方法调用名为GetUpdateCommand的方法,该方法具有带数据库更新命令的方法,我创建了一个变量cn,用于接收与bank的连接字符串,但是在尝试时打开连接并用try catch包围它,它没有找到带有连接的变量cn, 因为你找不到变量

public SqlCommand GetUpdateCommand()
    {

        //faz o for em que vai percorrer, traga somente os campos com o atributo customizado do tipo DataObjectFieldAttribute
        SqlCommand retorno = new SqlCommand();
        retorno.CommandText = "Update  {0}  set {1} where {2}";

        String tabela = typeof(T).Name;
        String campos = "";
        String chave = "";
        foreach (PropertyInfo pro in typeof(T).GetProperties().ToList().Where(p => p.GetCustomAttribute(typeof(DataObjectFieldAttribute)) != null))
        {
            DataObjectFieldAttribute att = (DataObjectFieldAttribute)pro.GetCustomAttribute(typeof(DataObjectFieldAttribute));

            if (att.PrimaryKey==true)//defini a chave primaria no DataObjectField na classe cliente colocando true
            {
                chave= pro.Name + "=@" + pro.Name;//pega a chava a chave primaria e adc no parametro
                retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this));//adicona os parametros
            }
            else
            {
                campos += pro.Name + "=@" + pro.Name + ",";
                retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this));
            }


        }
        //retorna com os parametros de acordo com o comando sql do uopdate.
        retorno.CommandText = String.Format(retorno.CommandText, tabela, campos,chave);

        return retorno;


    }

 public void atualizar()
    {

        using (SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|C:\Users\Antonio Viana\documents\visual studio 2017\Projects\Loja\Eccomerce\App_Data\dados.mdf;Integrated Security=True")) ;
        {

            SqlCommand cm = this.GetUpdateCommand();

            try
            {
                cn.Open();
            }
            catch (Exception)
            {

                throw;
            }

            cm.Connection = cn;
            cm.ExecuteNonQuery();
        }

    }

1 个答案:

答案 0 :(得分:1)

您通过使用using关闭using来关闭对象初始化后面;的范围。

所以这一行:

using (SqlConnection cn = new SqlConnection(...)) ;

应如下所示:

using (SqlConnection cn = new SqlConnection(...))