Batch sql & binding to repeater
Here is my first share from my .net learning experience.
This is the equivalent of using .NextRecordset() in classic asp.
You may find that in a page you need to collect several unrelated database result sets to render data in a page. If this is the case, quite often there is no need to connect to and call the database multiple times (wasting time and resources). We can make a batch call to the database by appending several queries separated by ";", we can then bind the results from meach query to separate data readers.
Code:
Private Sub BindArticles()
Dim objConnection As System.Data.Odbc.OdbcConnection
Dim strConn As String
Dim objCommand As New System.Data.Odbc.OdbcCommand
Dim strSQL As String
Dim rstArticles As System.Data.Odbc.OdbcDataReader
'Setup your connection and command - nothing special here
strConn = System.Configuration.ConfigurationManager.AppSettings("DatabaseString")
objConnection = New System.Data.Odbc.OdbcConnection(strConn)
objConnection.Open()
objCommand.Connection = objConnection
'Below notice how there are two separate queries within the strSQL variable
strSQL = "select * from table1 where type = 1 Order By title;" & _
"select * from table2 where type = 0 Order By title"
'Below we query the database, the method is exactly the same as requesting a single result set
objCommand.CommandText = strSQL
rstArticles = objCommand.ExecuteReader()
'By default we are using the first result set returned, check that the result set is not empty before binding to your page element
If rstArticles.Read Then
Repeater1.DataSource = rstArticles
Repeater1.DataBind()
End If
'Next is the magic command NextResult() - this will return a boolean specifying if there is another record set available
rstArticles.NextResult()
'We also need to check that this set of results is not empty before proceeding
If rstArticles.Read Then
Repeater2.DataSource = rstArticles
Repeater2.DataBind()
End If
'Always destroy your objects
rstArticles.Close()
objCommand.Dispose()
objConnection.Close()
End Sub
And that's all there is to it.
dr_rock, March 23rd, 2009 03:10 AM
Bookmarks