c# - Error: Object reference not set to an instance of an object./The connection was not closed. The connection's current state is open -
for longest time, code has been running, lately encounter error,object reference not set instance of object.
don't know if related creation , usage of new database.
here code:
con2.open(); sqlcommand cmd = new sqlcommand(); cmd.connection = con; cmd.commandtext = "select qtyinhand inventory productid=@productid"; cmd.parameters.add("@productid", sqldbtype.int).value = productid; int existingqty = (int)cmd.executescalar(); cmd.parameters.clear(); cmd.commandtext = "update inventory set qtyinhand=@qtyinhand productid=@productid"; cmd.parameters.add("@qtyinhand", sqldbtype.int).value = existingqty - int.parse(quantity); cmd.parameters.add("@productid", sqldbtype.int).value = productid; cmd.executenonquery(); con2.close();
error on part: int existingqty = (int)cmd.executescalar();
when tried using other sqlconnection: con
con.open(); sqlcommand cmd = new sqlcommand(); cmd.connection = con; cmd.commandtext = "select qtyinhand inventory productid=@productid"; cmd.parameters.add("@productid", sqldbtype.int).value = productid; int existingqty = (int)cmd.executescalar(); cmd.parameters.clear(); cmd.commandtext = "update inventory set qtyinhand=@qtyinhand productid=@productid"; cmd.parameters.add("@qtyinhand", sqldbtype.int).value = existingqty - int.parse(quantity); cmd.parameters.add("@productid", sqldbtype.int).value = productid; cmd.executenonquery(); con.close();
i encounter error, the connection not closed. connection's current state open.
error on con.open();
part. how should solve problem?
for first error, executescalar()
call returning null value. either refine query - can check query running directly in database - or change logic deal null values.
for second error, if calling open()
throwing error, it's because connection object in use before , not closed properly. it's considered bad practice reuse connections that, consider creating new connection instance when go opening one.
edit: tried imply in second paragraph there, feel must make explicit: don't forget deal connection left open there, may major performance hog application. specially since it's asp.net one. dispose of connections don't need them. when call dispose()
connection, gets closed - added bonus of other finer memory management procedures well. read using
statement , usage connections have time.
Comments
Post a Comment