0

I was wondering if the below way of handling multiple sql's within the same using statement is correct, I have tested this in a project and it works but would it not be better to wrap each sql in it's own using statement? Which option is a better coding practice?

Using cmd As New SqlCommand()

    cmd.Connection = conn
    cmd.CommandType = CommandType.Text

    sql = "Select * From blah"
    cmd.CommandText = sql
    theValue = cmd.ExecuteScalar()

    sql = "Update tbl1 Set a = b"
    cmd.CommandText = sql
    cmd.ExecuteScalar()

    sql = "Update tbl2 Set x = y"
    cmd.CommandText = sql
    cmd.ExecuteNonQuery()

End Using

Thanks

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
03Usr
  • 3,335
  • 6
  • 37
  • 63

2 Answers2

3

This is a bad practice and could potentially leak something.

I'm not even sure if Command.Close exists but you are missing:

sql = "Select * From blah"
cmd.CommandText = sql
theValue = cmd.ExecuteScalar()

cmd.Close()   ' you need something like this

sql = "Update tbl1 Set a = b"
cmd.CommandText = sql
cmd.ExecuteScalar()

The preferred way is of course not to reuse a Command oject. Create a new one for each action, and 1 Using per IDisposable object.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Thanks for the response. But I thought if we use the using statement we did not need to bother with `cmd.Close()`, because a Using block guarantees the disposal of resources when the code is finished with them? – 03Usr Aug 17 '12 at 17:33
  • 1
    The Using only assures that the resources of the _last_ Execute are released. Earlier Executes may also result in SQL handles being held, they will be overwritten but may not be freed here. To be sure you'd have to reflector ExecuteXxx – H H Aug 17 '12 at 18:09
2

Personally I would use a different SqlCommand object per execution.

With this simple script its easy to see what is happening, but if your scripts get more complicated and require Sql Parameters, you will have to remember to remove them after each execution (if they're not needed) otherwise an exception would be thrown.

Curtis
  • 101,612
  • 66
  • 270
  • 352