vb.net - ExecuteNonQuery() for Insert -


can please tell me what's wrong code?

do need use dataadapter insert table?

i know connectionstring ok, because tested on server explorer.

    dim mydao new connection     dim connectionstring string = mydao.getconnectionstring()     dim connection new sqlconnection(connectionstring)     dim cmd new sqlcommand  public function add(byval area string, byval user string) integer          cmd.commandtext = "insert area (area, user) values ('" + area + "','" + user + "')"         try             connection.open()             dim cant integer = cmd.executenonquery()'it throws exception here             connection.close()             return cant         catch ex exception             console.writeline(ex.message)             return 0         end try      end function 

the above code fails after executenonquery() , can´t figure why.

target fields (sql server 2008):

area        varchar(100)  not null , user        varchar(100)  not null  

the exception receive is: connection property has not initialized

there's few issues code.

the significant aren't setting command's connection property, command has no way of knowing how connect database.

i recommend utilizing using, , parameterizing query:

finally, don't declare connection , command outside of function unless need to. should keep connection , command around long need them.

so function end looking like:

public function add(byval area string, byval user string) integer      dim mydao new connection      using connection new sqlconnection(mydao.connectionstring())          using command new sqlcommand()             ' set connection             command.connection = connection               ' not necessary, practice             command.commandtype = commandtype.text               ' example query using parameters             command.commandtext = "insert area (area, user) values (@area, @user)"               ' adding parameters command             command.parameters.addwithvalue("@area", area)             command.parameters.addwithvalue("@user", user)              connection.open()              return command.executenonquery()          end using ' dispose command      end using ' dispose (and hence close) connection  end function 

note currently, returning 0 time. rather having check value returned function, above example throw exception. makes cleaner code (as caller have understand 0 error condition), and, if needed handle exception, wrap call function in try-catch block


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -