c# - Method update C # connection error -


this question has answer here:

i made method called update updates data in database,which calls method named getupdatecommand has method database update command,i created variable cn receives connection string bank,but when trying open connection , surround try catch, not find variable cn connection, because can not find variable

public sqlcommand getupdatecommand()     {          //faz o em que vai percorrer, traga somente os campos com o atributo customizado tipo dataobjectfieldattribute         sqlcommand retorno = new sqlcommand();         retorno.commandtext = "update  {0}  set {1} {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 chave primaria no dataobjectfield na classe cliente colocando true             {                 chave= pro.name + "=@" + pro.name;//pega chava 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 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();         }      } 

you're closing scope of using right behind object initialization closing using ;.

so line:

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

should this:

using (sqlconnection cn = new sqlconnection(...)) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -