"Ado.net 2.0 technical insider
We strongly recommend that youUsingCodeCreates short-lived objects at all possible locations in the block.
UsingBlock to ensure timelyUsingWhen an unhandled exception occurs in the block Inner Wave,It will also be called at the end of the code blockDisposeMethod.
Example:
String Strconn, strsql;
Strconn = @" Data Source =. \ sqlexpress; " + " Initial catalog = northwind; Integrated Security = true; " ;
Strsql = " Select customerid, companyName from MERs " ;
Using (sqlconnection CN = New Sqlconnection (strconn )){
Try {
CN. open ();
}
Catch (sqlexception ex ){
Consolse. writeline ( " Connect attempt failed " );
Consolse. writeline ( " {0} " , Ex. Message );
Return ;
}
Using (sqlcommand cmd = New Sqlcommand (strsql, CN ){
Try {
Using (Sqldatareader RDR = Cmd. executereader ()){
While (RDR. Read ())
Console. writeline (RDR [ " CompanyName " ]);
RDR. Close ();
}
}
Catch (Sqlexception ex ){
Console. writeline ( " Query failed " );
Console. writeline ( " {0} " , Ex. Message );
Return ;
}
}
CN. Close ();
}
"