2017-07-27 3 views
2

Ich habe eine Methode namens update, die die Daten in der Datenbank aktualisiert, die die Methode mit dem Namen GetUpdateCommand, die die Methode mit dem Datenbankaktualisierungsbefehl hat, ich habe eine Variable cn, die die Verbindungszeichenfolge mit erhält aufgerufen Bank, aber beim Versuch, die Verbindung zu öffnen und es mit einem try-catch umgibt, es findet nicht die Variable cn mit der Verbindung, Da Sie nicht die VariableMethode Update C# Verbindungsfehler

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 + "[email protected]" + 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 + "[email protected]" + 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

');' schließt den Umfang hinter 'using' – jAC

Antwort

1

Sie den Umfang sind Schließen finden using direkt hinter der Objektinitialisierung durch Schließen der using mit ;.

Also diese Zeile:

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

sollte wie folgt aussehen:

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

Nizza dort vor Ort @jAC – stuartd

+0

danken Arbeitete man Bruder – Felipe