c# - Do we need open db whendb is defined in using? -
When I use for connection, I know there is no need to use a pass or settlement. I wonder, do we need open access? Using
(var dbSqlConnection = New SqlConnection (ConfigurationSettings.AppSettings ["ConnectionString1"])) {dbSqlConnection.Open (); // It is necessary? }
It depends on you what you are doing ... if By manually executing a command using the SqlCommand object you will need to open the connection so that you can execute any command on the command. However, if you are using something like DataAdapter ... you do not need it because it will manage the connection for you. Using SqlCommand object ... (var dbSqlConnection = New SqlConnection (ConfigurationSettings.AppSettings ["ConnectionString1"] )) {Var cmd = New SqlCommand ("Your_Sql_Query", con); DbSqlConnection.Open (); // It is necessary? Cmd.ExecuteNonQuery (); } Using SqlDataAdapter ... using (var dbSqlConnection = New SqlConnection (ConfigurationSettings.AppSettings [ "ConnectionString1"])) {Dataset DS = new dataset (); SqlDataAdapter Adapter = New SqlDataAdapter (); Adapters. Selection Commands = New SQL Commands (QueryString, DBSQL Connection); Adapter.fill (ds); }
Note that SqlDataAdapter will handle the connection for you, it will open and dispose it
Comments
Post a Comment