Connection property has not been initialized c# -
im getting when execute non query .. calling executenonquery....
clsconnection.executenonquery("add_customers", commandtype.storedprocedure, paramlist);
exception pop @ cmd.connection.open();
this whole executenonquery
public static void executenonquery(string sql, commandtype type, list<sqlparameter> paramlist) try { dataaccess.clsconnection clsdb = new dataaccess.clsconnection(); using (sqlconnection cn =clsdb.opencon()) { sqlcommand cmd = new sqlcommand(); cmd = createcommand(sql, type, paramlist); cmd.connection = cn; cmd.commandtype = type; cmd.commandtext = sql; cmd.executenonquery(); }
you don't assign connection object command
when sqlcommand executes query needs open connection. first step search connection property see if has been initialized. property null , error
simply fix with
cmd.connection = maincon;
of course, have opened connection , don't need line
cmd.connection.open();
said that, suggest avoid keep global connection object in way. better performance , impact on system resources used program change opencon return connection opened , use using statement free resource when no more needed
namespace dataaccess { public class clsconnection { public sqlconnection opencon() { dbn = "pms"; server = "server-pc\\sqlexpress"; user = "sa"; pwd = "sysadmin123"; sqlconnection cn = new sqlconnection("initial catalog=" + dbn + ";data source=" + server + "; user id =" + user + "; password =" + pwd + ";connect timeout=10"); ..... cn.open(); return cn; } } }
so code use connection changed to
try { dataaccess.clsconnection clsdb = new dataaccess.clsconnection(); using(sqlconnection cn = clsdb.opencon()) { sqlcommand cmd = new sqlcommand(); cmd = createcommand(sql, type, paramlist); cmd.connection = cn; cmd.commandtype = type; cmd.commandtext = sql; cmd.executenonquery(); // here closing braces closes , disposes connection freeing resources used // in case of exceptions } } catch (exception ex) { .... }
edit: seeing comment below, added more context method opencon. suggest change code , take advantage of using statement
Comments
Post a Comment