[RESOLVED] When to open Database Connection
Hi,
I created project recently. I created my connection on startup with the connection string. Originally I thought you have to use connection.open each time you wanted to fill a dataadapter and dataset. But, I found a couple of spots that I forgot to use connection.open before filling them and it worked anyway. My question is, when do you have to use connection.open?
Thanks
Re: When to open Database Connection
Fill will implicitly open the connection if it's not already. If it had to open the connection it will also close it again. If you intend to make multiple calls to Fill you should explicitly open and close the connection to prevent it being done implicitly between each call, which slows things down. Also, you have to open the connection explicitly when calling ExecuteReader, ExecuteScalar and ExecuteNonQuery on a Command.
Re: When to open Database Connection
What about update commands? If I use the update command after a fill, will the fill close the connection before my update command is ran? Or does the fill command close the connection at the end of the code?
Re: When to open Database Connection
Update is like Fill in that it will open the connection if it needs to. It will then leave the connection in the state it found it. Update should be used in the same way as Fill in my previous post. If you're making multiple calls to Fill nad/or Update in quick succession then you should explicitly open and close the connection.