Example:
If some condition is true then
Dim da As New SqlDataAdapter,...
da.SelectCommand = New SqlCommand
da.InsertCommand = New SqlCommand
...
da.InsertCommand.Parameters.Add(...)
...
da.InsertCommand.Parameters.Add(...)
....
If conn.State = ConnectionState.Closed Then conn.Open
...
da.SelectCommand.ExecuteNonQuery
...
da.Update(ds, "someTbl")
...
End If
...
If conn.State = ConnectionState.Open Then conn.Close
...
End If
I supposed I could write a bunch of little subs and functions to handle the
stuff, but that would be more stuff to maintain and bounce around when I have
to debug or update something. Some of these If blocks might have 50 lines
which isn't that bad except when you have a bunch of nested if statements.
Well, I guess I can use bookmarks.
- Show quoted text -
Actually, looking at your code I can make three suggestions. First,
don't trust the ConnectionState property, it only returns what it
*thinks* it's state is. It may return that it is Open, and then throw
an exception because it's closed whenever you use it. I highly
recommend you ditch the if...then test and just use a try catch block
to make sure every succeeds. Secondly, I would remove the "If
conn.State = ConnectionState.Open Then conn.Close" block and wrap the
whole sucker in a using block. Then you can ensure that it will
properly close itself and release any non-managed resources. Lastly,
the other Db object should also be disposed of when you are finished
with them. I would recommend you use a Using block, but you could also
use a try...finally structure too. Disposing is a hotly debated topic,
but in my opinion is what you should do to ensure smooth and
performant execution of your code.
Thanks,
Seth Rowe