You are right: your connection will not be closed in this way. Worse, only by accepting strings for your sqlcommand do you open yourself up for sql injection security vulnerabilities. As an example of a better template, the code I use to populate the data table is as follows:
Public Function GetDataTable(ByVal sql As String, ByVal AddParameters As Action(Of SqlParameterCollection)) As DataTable Dim result As New DataTable() Using cn As SqlConnection = OpenConn(), _ cmd As New SqlCommand(sql, cn) AddParameters(cmd.Parameters) Using rdr As SqlDataReader = cmd.ExecuteReader result.Load(rdr) End Using End Using Return result End Function
Then I would call the code as follows:
Dim data As DataTable = GetDataTable("SELECT * FROM SomeTable WHERE ID= @ID", _ Sub(p) p.Add("@ID", SqlDbType.Int).Value = 12345 End Sub )
I have similar code in C # for SqlDataReader, but it needs to use an iterator block, and this feature is not available for VB, it was just added to VB.Net with the service pack for visual studio 2010 and Async CTP a few weeks ago. The important thing to clean up here is that I have a sql connection correctly encapsulated by the Using block, and the code encourages the correct use of query parameters.
source share