Search code examples
vb.netusingsqlcommand

Multiple or single 'using' statements?


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


Solution

  • 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.