What is the use of Connection Open method in ADO.Net

Last Reply on Jul 05, 2013 06:30 AM By RkHirpara

Posted on Jul 05, 2013 02:01 AM

we usually open a connection by con.open() and close the connection by con.close().when we create a method like,

public void conopen()

{

if(connectionstate.open)

con.open();

con.close();

}

what is basically the use of this method..??...why we create this method when we have co.open() and con.close();

Posted on Jul 05, 2013 05:47 AM

Hi kripisaxena,

Whatever conopen() method you have pasted is not an universal approach, the approach to open and close a connection is varies from programmer to programmer, architecture to architecture.

However Concering .Net languages, the connection.Open and Connection.Close are the two method, where connection is an object of SqlConnection class.

After setting relavent properties you need to establish a connection between your application and Database server. Connection is a resource so it should open as less duration as its indeed required to open therefore, after finishing connections task firing queries, we should imediately close the connection. For that we are using SqlConnecion.Close method.

Thanks and Regards,

Rk_Hirpara


Posted on Jul 05, 2013 05:53 AM

for example,I use in one mthod i use two sqlqueries, one sqlquery with datareader it will require open connection con.open() then after reading we do con.close then immediately we use second query then open connection for it and then again close it by co.close()..But still sometimes happpen that we get error like connection remains open..we have closed the connections but still we get error...but when we use that method it doesnt give error..so i just want to know then why programmers use this method..


Posted on Jul 05, 2013 06:30 AM

Hi Kripisaxena,

Whatever scenario you are presenting is technically impossible. because once you are closing the connection it has to be close there is no other option. but the case might be like that the connection object is a class member and in whichever method you closed that connection might not executed due to some exception and if the try - catch is used its handled by the catch (So the Connection.Close() is not executed at all) and as the conn object is declared as class member you are using that method successively and you couldnot close the connection object in last call(which was handled by the catch) the connection is in open state so you will get the error.

How ever better to check the ConnectionState.

Thanks and Regards,

Rk_Hirpara