I recently posted (and promptly deleted, when I decided the question was irrelevant to the actual problem) a question about SqlConnection losing its Database information when the scope of “ChangeDatabase” ends. Example:
//Other code...
dbConn = new SqlConnection(dbConnBuilder.ConnectionString);
dbConn.Open();
dbConn.ChangeDatabase(currentDatabase);
dbConn.Close();
}
My questions:
- Is it considered bad practice to hold onto a
SqlConnectionobject and open and close it whenever you need it when you’ll only ever have ONE connection of a given type? - Why does
dbConn.Databasenot remembercurrentDatabaseafter ChangeDatabase (a method not a variable) ‘Goes out of scope’? (Heck, I didn’t know methods likeChangeDatabasecould know about scope).
My connection string was:
Data Source=server.name.com;Persist Security Info=True;User ID=username;Password=password
Thanks guys, let me know if I can give you more information, still learning to use S.O.
Calling
Close()completely destroys the object, so you should not be reading any of its properties after.In fact, there should even be an “after” because you shouldn’t be calling
Close(). Instead, instantiate the connection in ausingblock, so that it’ll callDispose(), which does the same thing asClose(), but is guaranteed to do so no matter how you leave the block.