2017-07-27 36 views
2

我做了一個名爲update的方法來更新數據庫中的數據,它調用名爲GetUpdateCommand的方法,該方法使用數據庫更新命令,我創建了一個變量cn,它接收連接字符串銀行,但試圖打開連接和一個嘗試捕捉圍繞着它的時候,它不會與連接找到變量CN, 因爲你無法找到變量方法更新C#連接錯誤

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

')'關閉落後'using' – jAC

回答

1

您要關閉的範圍using右對齊通過關閉using;對象初始化。

所以這行:

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

應該是這樣的:

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

好地方有@jAC – stuartd

+0

曾爲謝謝哥哥範圍 – Felipe