Interacting with Databases Using ASP.NET 2.0 with the Microsoft Data Access Application Block - Retrieving a single value using the Data Access Application Block
(Page 4 of 6 )
In this section, we shall retrieve a single value onto the form by passing a SELECT statement to the Data Access Application Block.
The following is the complete code:
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Me.lblMsg.Text = getSingleValue("select count(*) from
HumanResources.department")
End Sub
Private Function getSingleValue(ByVal SQl As String) As
String
Dim db As SqlDatabase = DirectCast
(DatabaseFactory.CreateDatabase("AdventureWorks"), SqlDatabase)
Dim dt As DataTable = db.ExecuteDataSet(CommandType.Text,
SQl).Tables(0)
Return dt.Rows(0)(0) & ""
End Function
EndClass
In the above code, there is nothing much to explain. Up to now, I didn’t implement exception handling in any of the above code. Just to help you understand, we can even handle errors efficiently by rewriting the above program as follows:
ImportsSystem.Data
ImportsMicrosoft.Practices.EnterpriseLibrary.Data.Sql
ImportsMicrosoft.Practices.EnterpriseLibrary.Data
PartialClass _Default
Inherits System.Web.UI.Page
Protected Sub btnConnect_Click(ByVal sender As Object, ByVal
e As System.EventArgs) Handles btnConnect.Click
Try
Me.lblMsg.Text = getSingleValue("select count(*) from
HumanResources.department")
Catch ex As Exception
Me.lblMsg.Text = ex.Message
End Try
End Sub
Private Function getSingleValue(ByVal SQl As String) As String
Try
Dim db As SqlDatabase = DirectCast
(DatabaseFactory.CreateDatabase("AdventureWorks"), SqlDatabase)
Dim dt As DataTable = db.ExecuteDataSet
(CommandType.Text, SQl).Tables(0)
Return dt.Rows(0)(0) & ""
Catch ex As Exception
Throw New Exception("Unable to retrieve value:" &
ex.Message)
End Try
End Function
EndClass
Next: Executing a DML statement using the Data Access Application Block >>
More ASP.NET Articles
More By Jagadish Chaterjee